/**
 * Time Metrics Generators Definitions
 *
 * This file contains generator functions for each block defined in
 * time_metrics_blocks.js. Each generator translates a Blockly block into a JSON
 * object representing time metrics retrieval operations.
 */

export function defineTimeMetricsGenerators() {

    // Ensure the base generator is initialized and 'createOperationObject' is available
    if (!Blockly.JSON || !Blockly.JSON.createOperationObject) {
        console.error("Blockly.JSON or createOperationObject not initialized. Please ensure 'json_base_generator.js' is loaded first.");
        return;
    }

    /**
     * Helper Function: validateTimeUnit
     * Validates the time unit and returns a default if invalid.
     *
     * @param {string} timeUnit - The time unit to validate.
     * @returns {string} - Validated time unit.
     */
    function validateTimeUnit(timeUnit) {
        const validUnits = ['seconds', 'minutes', 'hours'];
        if (!validUnits.includes(timeUnit)) {
            console.error(`Invalid time unit '${timeUnit}' in 'time_since_start' block. Defaulting to 'seconds'.`);
            return 'seconds';
        }
        return timeUnit;
    }

    /**
     * Generator for 'time_since_start' Block
     */
    Blockly.JSON['time_since_start'] = function(block) {
        const timeUnit = block.getFieldValue('TIME_UNIT') || 'seconds';
        const validatedTimeUnit = validateTimeUnit(timeUnit);

        const operationObject = Blockly.JSON.createOperationObject('time_since_start', {unit: validatedTimeUnit} );

        // Prepare output, handling any additional values
        const outputValues = [operationObject];
        const valuesArray = Blockly.JSON.processValuesInput(block);
        if (valuesArray.length > 0) {
            outputValues.push(...valuesArray);
        }

        return {
            type: 'dynamic_value',
            values: outputValues
        };
    };
}
