// client/indicator_blocks.js

// Define Blockly blocks and their JSON generators dynamically based on indicators
export function defineIndicatorBlocks() {

    // Ensure Blockly.JSON is available
    if (!Blockly.JSON) {
        console.error('Blockly.JSON is not defined. Ensure json_generators.js is loaded before indicator_blocks.js.');
        return;
    }

    // Retrieve the indicator outputs configuration
    const indicatorOutputs = window.UI.indicators.getIndicatorOutputs();
    const toolboxCategory = document.querySelector('#toolbox_advanced category[name="Indicators"]');

    if (!toolboxCategory) {
        console.error('Indicators category not found in the toolbox.');
        return;
    }

    // Check if there are any indicators to display
    const indicatorNames = Object.keys(indicatorOutputs);
    if (indicatorNames.length === 0) {
        // Add helpful message when no indicators exist
        const labelElement = document.createElement('label');
        labelElement.setAttribute('text', 'No indicators configured yet.');
        toolboxCategory.appendChild(labelElement);

        const labelElement2 = document.createElement('label');
        labelElement2.setAttribute('text', 'Add indicators from the Indicators panel');
        toolboxCategory.appendChild(labelElement2);

        const labelElement3 = document.createElement('label');
        labelElement3.setAttribute('text', 'on the right side of the screen.');
        toolboxCategory.appendChild(labelElement3);

        console.log('No indicators available - added help message to toolbox.');
        return;
    }

    for (let indicatorName in indicatorOutputs) {
        const outputs = indicatorOutputs[indicatorName];

        // Create a unique block type by replacing spaces with underscores
        const sanitizedIndicatorName = indicatorName.replace(/\s+/g, '_'); // Replace spaces with underscores
        const blockType = 'indicator_' + sanitizedIndicatorName;

        // Define the block for this indicator
        Blockly.defineBlocksWithJsonArray([{
            "type": blockType,
            "message0": `${indicatorName} Output %1`,
            "args0": [
                {
                    "type": "field_dropdown",
                    "name": "OUTPUT",
                    "options": outputs.map(output => [output, output])
                }
            ],
            "output": "dynamic_value",
            "colour": 230,
            "tooltip": `Select the ${indicatorName} output`,
            "helpUrl": ""
        }]);

        // Define the JSON generator for this block
        Blockly.JSON[blockType] = function(block) {
            const selectedOutput = block.getFieldValue('OUTPUT');
            const json = {
                type: 'indicator',
                fields: {
                    NAME: indicatorName,
                    OUTPUT: selectedOutput
                }
            };
            // Output as dynamic_value
            return {
                type: 'dynamic_value',
                values: [json]
            };
        };

        // Append the newly created block to the Indicators category in the toolbox
        const blockElement = document.createElement('block');
        blockElement.setAttribute('type', blockType);
        toolboxCategory.appendChild(blockElement);
    }

    console.log('Indicator blocks and their JSON generators have been defined and inserted into the toolbox.');
}
