/**
 * logic_if_mutator.js
 * Erweiterbarer WENN-DANN-SONST Block mit integrierten +/- Buttons
 * Angepasst für den custom ArduinoGenerator
 */

// Base64 Icons (Weiß) für die Buttons, komplett offline-fähig
const ICON_PLUS = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ij48cGF0aCBmaWxsPSIjZmZmZmZmIiBkPSJNMTkgMTNoLTZ2NmgtMnYtNkg1di0yaDZVNWgydjZoNnYyeiIvPjwvc3ZnPg==';
const ICON_MINUS = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2Ij48cGF0aCBmaWxsPSIjZmZmZmZmIiBkPSJNMTkgMTNINXYtMmgxNHYyeiIvPjwvc3ZnPg==';

// =======================================================================
// 1. BLOCK-DEFINITION (UI & VERHALTEN)
// =======================================================================
Blockly.Blocks['ard_logic_if_plus'] = {
    init: function() {
        this.setColour(230); // Standard Logik-Farbe aus deiner Toolbox
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip('Dynamische Wenn-Dann-Sonst Verzweigung. Nutze die Tasten unten zum Erweitern.');
        
        // Zähler für die dynamischen Zweige
        this.elseifCount_ = 0;
        this.elseCount_ = 0;
        
        // Feste Basis-Eingänge
        this.appendValueInput('IF0')
            .setCheck(['Boolean', 'Number'])
            .appendField('WENN');
        this.appendStatementInput('DO0')
            .appendField('DANN');
            
        this.updateShape_();
    },
    
    // Sichern der Struktur beim Speichern (XML)
    mutationToDom: function() {
        var container = Blockly.utils.xml.createElement('mutation');
        if (this.elseifCount_) {
            container.setAttribute('elseif', this.elseifCount_);
        }
        if (this.elseCount_) {
            container.setAttribute('else', 1);
        }
        return container;
    },
    
    // Wiederherstellen der Struktur beim Laden (XML)
    domToMutation: function(xmlElement) {
        this.elseifCount_ = parseInt(xmlElement.getAttribute('elseif'), 10) || 0;
        this.elseCount_ = parseInt(xmlElement.getAttribute('else'), 10) || 0;
        this.updateShape_();
    },
    
    // Button-Funktionen
    addElseIf_: function() {
        this.elseifCount_++;
        this.updateShape_();
    },
    removeElseIf_: function() {
        if (this.elseifCount_ > 0) {
            this.elseifCount_--;
            this.updateShape_();
        }
    },
    addElse_: function() {
        this.elseCount_ = 1;
        this.updateShape_();
    },
    removeElse_: function() {
        this.elseCount_ = 0;
        this.updateShape_();
    },
    
    // Dynamischer Aufbau des Blocks
    updateShape_: function() {
        // Verbindungen temporär sichern, um Blöcke beim Neuladen nicht abzureißen
        var elseIfConnections = [];
        var elseIfDoConnections = [];
        for (var i = 1; i <= this.elseifCount_ + 1; i++) { 
            elseIfConnections.push(this.getInput('IF' + i) ? this.getInput('IF' + i).connection.targetConnection : null);
            elseIfDoConnections.push(this.getInput('DO' + i) ? this.getInput('DO' + i).connection.targetConnection : null);
        }
        var elseConnection = this.getInput('ELSE') ? this.getInput('ELSE').connection.targetConnection : null;

        // Alte dynamische Inputs restlos entfernen
        for (var i = 1; this.getInput('IF' + i); i++) {
            this.removeInput('IF' + i);
            this.removeInput('DO' + i);
        }
        if (this.getInput('ELSE')) {
            this.removeInput('ELSE');
        }
        if (this.getInput('BUTTONS')) {
            this.removeInput('BUTTONS');
        }

        // SONST WENN Zweige neu aufbauen
        for (var i = 1; i <= this.elseifCount_; i++) {
            var ifInput = this.appendValueInput('IF' + i)
                              .setCheck(['Boolean', 'Number'])
                              .appendField('SONST WENN');
            var doInput = this.appendStatementInput('DO' + i)
                              .appendField('DANN');
                              
            // Gesicherte Verbindungen wiederherstellen
            if (elseIfConnections[i - 1]) ifInput.connection.connect(elseIfConnections[i - 1]);
            if (elseIfDoConnections[i - 1]) doInput.connection.connect(elseIfDoConnections[i - 1]);
        }

        // SONST Zweig neu aufbauen
        if (this.elseCount_) {
            var elseInput = this.appendStatementInput('ELSE')
                                .appendField('SONST');
            if (elseConnection) elseInput.connection.connect(elseConnection);
        }

        // Steuer-Buttons am unteren Rand einfügen
        var btnInput = this.appendDummyInput('BUTTONS').setAlign(Blockly.ALIGN_RIGHT);
        
        btnInput.appendField(new Blockly.FieldImage(ICON_PLUS, 18, 18, '+', () => this.addElseIf_()));
        btnInput.appendField(' Sonst Wenn');
        
        if (this.elseifCount_ > 0) {
            btnInput.appendField('  ');
            btnInput.appendField(new Blockly.FieldImage(ICON_MINUS, 18, 18, '-', () => this.removeElseIf_()));
        }

        btnInput.appendField('   |   ');

        if (!this.elseCount_) {
            btnInput.appendField(new Blockly.FieldImage(ICON_PLUS, 18, 18, '+', () => this.addElse_()));
            btnInput.appendField(' Sonst');
        } else {
            btnInput.appendField(new Blockly.FieldImage(ICON_MINUS, 18, 18, '-', () => this.removeElse_()));
            btnInput.appendField(' Sonst');
        }
    }
};

// =======================================================================
// 2. GENERATOR-LOGIK (C++ CODE ERZEUGUNG)
// =======================================================================
ArduinoGenerator.forBlock['ard_logic_if_plus'] = function(block) {
    let code = '';
    
    // Erster WENN-DANN Zweig
    // Die 0 steht für ArduinoGenerator.PRECEDENCE (wie im Core definiert)
    let conditionCode = ArduinoGenerator.valueToCode(block, 'IF0', 0) || 'false';
    let branchCode = ArduinoGenerator.statementToCode(block, 'DO0');
    code += '  if (' + conditionCode + ') {\n' + branchCode + '  }';

    // SONST WENN Zweige iterieren
    for (let n = 1; n <= block.elseifCount_; n++) {
        conditionCode = ArduinoGenerator.valueToCode(block, 'IF' + n, 0) || 'false';
        branchCode = ArduinoGenerator.statementToCode(block, 'DO' + n);
        code += ' else if (' + conditionCode + ') {\n' + branchCode + '  }';
    }

    // SONST Zweig anhängen (falls vorhanden)
    if (block.elseCount_) {
        branchCode = ArduinoGenerator.statementToCode(block, 'ELSE');
        code += ' else {\n' + branchCode + '  }';
    }

    return code + '\n';
};