/**
 * Control Generators Definitions
 *
 * This file contains generator functions for each block defined in
 * control_blocks.js. Each generator translates a Blockly block
 * into a JSON object representing control operations.
 */

export function defineControlGenerators() {

    // 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;
    }

    /**
     * Generator for 'pause_strategy' Block
     */
//    Blockly.JSON['pause_strategy'] = function(block) {
//        const json = {
//            type: 'pause_strategy'
//        };
//
//        return json; // Return the JSON object directly
//    };

    /**
     * Generator for 'strategy_resume' Block
     */
//    Blockly.JSON['strategy_resume'] = function(block) {
//        const json = {
//            type: 'strategy_resume'
//        };
//
//        return json; // Return the JSON object directly
//    };

    /**
     * Generator for 'strategy_exit' Block
     */
//    Blockly.JSON['strategy_exit'] = function(block) {
//        const conditionValue = block.getFieldValue('condition'); // 'all', 'in_profit', 'in_loss'
//
//        const json = {
//            type: 'strategy_exit',
//            inputs: {
//                condition: conditionValue
//            }
//        };
//
//        return json; // Return the JSON object directly
//    };

    /**
     * Generator for 'max_drawdown' Block
     */
    Blockly.JSON['max_drawdown'] = function(block) {
        const action = block.getFieldValue('ACTION'); // 'PAUSE' or 'EXIT'

        // Retrieve the drawdown value from 'DRAWDOWN_VALUE' input
        let drawdownValue = 0;
        const drawdownBlock = block.getInputTargetBlock('DRAWDOWN_VALUE');
        if (drawdownBlock) {
            drawdownValue = Blockly.JSON.blockToCode(drawdownBlock);
            if (typeof drawdownValue !== 'number') {
                console.error("Invalid drawdown value in 'max_drawdown' block.");
                drawdownValue = 0;
            }
        } else {
            console.warn("No drawdown value provided in 'max_drawdown' block. Using default value 0.");
        }

        const json = {
            type: 'max_drawdown',
            inputs: {
                drawdown: drawdownValue,
                action: action
            }
        };

        return json; // Return the JSON object directly
    };

    /**
     * Generator for 'schedule_action' Block
     */
    Blockly.JSON['schedule_action'] = function(block) {
        // Retrieve the time interval from dropdown
        const timeInterval = block.getFieldValue('TIME_INTERVAL'); // e.g., '1m', '5m', etc.
        // Retrieve the repeat option
        const repeatOption = block.getFieldValue('REPEAT'); // 'ONCE' or 'REPEAT'

        // Create operation object
        const operationObject = {
            type: 'schedule_action',
            inputs: {
                time_interval: timeInterval,
                repeat: repeatOption === 'REPEAT' // true if 'REPEAT', false if 'ONCE'
            }
        };

        // Process the 'DO' statements
        const actionJsonArray = [];
        let currentBlock = block.getInputTargetBlock('DO');
        while (currentBlock) {
            const blockJson = Blockly.JSON.blockToCode(currentBlock);
            if (blockJson) {
                actionJsonArray.push(blockJson);
            }
            currentBlock = currentBlock.getNextBlock();
        }

        // Include the nested statements if any
        if (actionJsonArray.length > 0) {
            operationObject.inputs.action = actionJsonArray;
        }

        return operationObject; // Return the JSON object directly
    };

    /**
     * Generator for 'execute_if' Block
     */
    Blockly.JSON['execute_if'] = function(block) {
        try {
            // Process CONDITION input
            let conditionJson = null;
            const conditionBlock = block.getInputTargetBlock('CONDITION');
            if (conditionBlock) {
                conditionJson = Blockly.JSON._blockToJson(conditionBlock, 1);
                if (typeof conditionJson !== 'object' || conditionJson === null) {
                    console.error(`Invalid 'CONDITION' input in 'execute_if' block. Expected an object.`);
                    conditionJson = { type: 'comparison', operator: '==', inputs: { LEFT: 0, RIGHT: 0 } }; // Default condition
                }
            } else {
                console.warn(`No block connected to 'CONDITION' input of 'execute_if' block. Using default condition.`);
                conditionJson = { type: 'comparison', operator: '==', inputs: { LEFT: 0, RIGHT: 0 } }; // Default condition
            }

            // Process DO statements
            const doStatements = [];
            let currentBlock = block.getInputTargetBlock('DO');
            if (currentBlock) {
                const blockJson = Blockly.JSON._blockToJson(currentBlock, 1);
                if (blockJson) {
                    doStatements.push(blockJson);
                }
                // No need to handle 'next' here, as _blockToJson will process it
            }

            // If no DO statements, exclude the block
            if (doStatements.length === 0) {
                console.warn(`'execute_if' block has no DO statements. Excluding from JSON.`);
                return null; // Exclude the block
            }

            // **Construct the JSON object**
            const json = {
                type: 'execute_if',
                inputs: {
                    CONDITION: conditionJson
                },
                statements: {
                    DO: doStatements
                }
            };

            // // **Set the skipAdditionalParsing flag**
            // json.skipAdditionalParsing = true;

            console.log(`Generated JSON for 'execute_if' block:`, json);
            return json;
        } catch (error) {
            console.error(`Error in generator for 'execute_if' block:`, error);
            return null; // Return null to indicate failure
        }
    };


}
