// =======================================================================
// LOGIKKISTE - JOYSTICK SHIELD
// =======================================================================

Blockly.defineBlocksWithJsonArray([

    // --- 1. SHIELD: TASTER (Feste Pins) ---
    {
        "type": "ard_shield_joy_button",
        "message0": "Shield Taster %1 erkennt %2",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "BUTTON",
                "options": [
                    ["A (Rechts)", "2"],
                    ["B (Unten)", "3"],
                    ["C (Links)", "4"],
                    ["D (Oben)", "5"],
                    ["E (Ext 1)", "6"],
                    ["F (Ext 2)", "7"],
                    ["K (Joystick Klick)", "8"]
                ]
            },
            {
                "type": "field_dropdown",
                "name": "ACTION",
                "options": [
                    ["Einfachklick", "KK_SINGLE_CLICK"],
                    ["Doppelklick", "KK_DOUBLE_CLICK"],
                    ["Halten (Lang)", "KK_LONG_PRESS"],
                    ["Wird gerade gedrückt", "IS_PRESSED"],
                    ["Wurde soeben losgelassen", "WAS_RELEASED"]
                ]
            }
        ],
        "output": "Boolean",
        "colour": 45, 
        "tooltip": "Fragt die Taster auf dem Joystick-Shield (A-F, K) mit Profi-Funktionen ab."
    },

    // --- 2. SHIELD: JOYSTICK RICHTUNG ---
    {
        "type": "ard_shield_joy_dir",
        "message0": "Joystick wird bewegt nach %1",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "DIR",
                "options": [
                    ["Mitte (Losgelassen)", "0"],
                    ["⬆️ Oben", "1"],
                    ["⬇️ Unten", "2"],
                    ["⬅️ Links", "3"],
                    ["➡️ Rechts", "4"],
                    ["↖️ Oben-Links", "5"],
                    ["↗️ Oben-Rechts", "6"],
                    ["↙️ Unten-Links", "7"],
                    ["↘️ Unten-Rechts", "8"]
                ]
            }
        ],
        "output": "Boolean",
        "colour": 45,
        "tooltip": "Wertet die analogen X/Y Achsen (A0/A1) intelligent als Richtungen aus."
    },

    // --- 3. SHIELD: JOYSTICK WERT (X/Y) ---
    {
        "type": "ard_shield_joy_val",
        "message0": "Lese Joystick Achse %1",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "AXIS",
                "options": [
                    ["X-Achse (Links/Rechts)", "A0"],
                    ["Y-Achse (Oben/Unten)", "A1"]
                ]
            }
        ],
        "output": "Number",
        "colour": 45,
        "tooltip": "Gibt den rohen analogen Wert (0-1023) der Achse zurück."
    }
]);


// =======================================================================
// C++ CODE GENERATOREN
// =======================================================================

// --- HILFSFUNKTION FÜR SHIELD TASTER ---
function generateShieldButtonCode(pinCode, action, blockId) {
    let btnName = `btnPro_${pinCode}`;
    
    // Globale Instanz und Library einbinden
    ArduinoGenerator.globals_.add(`#include "KK_ButtonHandler.h"`);
    ArduinoGenerator.globals_.add(`KK_ButtonHandler ${btnName}(${pinCode});`);
    
    // Auto-Setup und Auto-Loop (wird von ArduinoGenerator automatisch an die richtige Stelle gepackt)
    if (!ArduinoGenerator.autoSetup_.includes(`  ${btnName}.begin();\n`)) {
        ArduinoGenerator.autoSetup_.push(`  ${btnName}.begin();\n`);
    }
    if (!ArduinoGenerator.autoLoop_.includes(`  ${btnName}.update();\n`)) {
        ArduinoGenerator.autoLoop_.push(`  ${btnName}.update();\n`);
    }

    // Welcher C++ Code soll für die jeweilige Aktion generiert werden?
    if (action === "IS_PRESSED") {
        return [`${btnName}.isPressed()`, 0];
    } else if (action === "WAS_RELEASED") {
        return [`${btnName}.wasReleased()`, 0];
    } else {
        // Die Events (Single, Double, Long)
        return [`(${btnName}.getEvent() == ${action})`, 0];
    }
}

// 1. GENERATOR: SHIELD TASTER
ArduinoGenerator.forBlock['ard_shield_joy_button'] = function(block) {
    const pin = block.getFieldValue('BUTTON');
    const action = block.getFieldValue('ACTION');
    return generateShieldButtonCode(pin, action, block.id);
};

// 2. GENERATOR: JOYSTICK RICHTUNG
ArduinoGenerator.forBlock['ard_shield_joy_dir'] = function(block) {
    const dir = block.getFieldValue('DIR');

    // Wir erstellen eine smarte Hilfsfunktion im C++ Code für die Richtungen
    ArduinoGenerator.globals_.add(`
uint8_t getJoystickDir() {
  int x = analogRead(A0);
  int y = analogRead(A1);
  bool right = x > 600;
  bool left = x < 400;
  bool up = y > 600;
  bool down = y < 400;

  if (up && left) return 5;
  if (up && right) return 6;
  if (down && left) return 7;
  if (down && right) return 8;
  if (up) return 1;
  if (down) return 2;
  if (left) return 3;
  if (right) return 4;
  return 0; // Mitte
}
`);

    return [`(getJoystickDir() == ${dir})`, 0];
};

// 3. GENERATOR: JOYSTICK WERT (ROH)
ArduinoGenerator.forBlock['ard_shield_joy_val'] = function(block) {
    const axis = block.getFieldValue('AXIS');
    return [`analogRead(${axis})`, 0];
};