// =======================================================================
// LOGIKKISTE - ARDUINO LCD KEYPAD SHIELD
// =======================================================================

const LCD_KEYPAD_COLOR = 210;

// =======================================================================
// 1. BLOCK-DEFINITIONEN (Aussehen in Blockly)
// =======================================================================

Blockly.defineBlocksWithJsonArray([
    // --- 1. SETUP BLOCK ---
    {
        "type": "lcd_keypad_setup",
        "message0": "Setup LCD Keypad Shield %1 Schwellenwerte: %2 Right %3 Up %4 Down %5 Left %6 Select %7",
        "args0": [
            {"type": "input_dummy"},
            {"type": "input_dummy"},
            {"type": "field_number", "name": "TH_RIGHT", "value": 50},
            {"type": "field_number", "name": "TH_UP", "value": 195},
            {"type": "field_number", "name": "TH_DOWN", "value": 380},
            {"type": "field_number", "name": "TH_LEFT", "value": 555},
            {"type": "field_number", "name": "TH_SELECT", "value": 790}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": LCD_KEYPAD_COLOR,
        "tooltip": "Initialisiert das LCD Keypad Shield an den Standard-Pins (8,9,4,5,6,7) und A0. Muss in den SETUP-Bereich."
    },

    // --- 2a. SCHREIBEN BLOCK (Normal) ---
    {
        "type": "lcd_keypad_print",
        "message0": "LCD Shield Schreibe: %1",
        "args0": [
            {"type": "input_value", "name": "TEXT"}
        ],
        "message1": "in Zeile: %1 Spalte: %2",
        "args1": [
            {"type": "input_value", "name": "ROW", "check": "Number"},
            {"type": "input_value", "name": "COL", "check": "Number"}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": LCD_KEYPAD_COLOR,
        "tooltip": "Schreibt einen Text oder eine Variable auf das LCD. Zeile (0-1), Spalte (0-15)."
    },

    // --- 2b. ÜBERSCHREIBEN BLOCK (Gegen Geister-Ziffern) ---
    {
        "type": "lcd_keypad_print_overwrite",
        "message0": "LCD Shield Überschreibe mit: %1",
        "args0": [
            {"type": "input_value", "name": "TEXT"}
        ],
        "message1": "in Zeile: %1 Spalte: %2",
        "args1": [
            {"type": "input_value", "name": "ROW", "check": "Number"},
            {"type": "input_value", "name": "COL", "check": "Number"}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": LCD_KEYPAD_COLOR,
        "tooltip": "Schreibt den Wert und hängt Leerzeichen an, um alte, längere Werte nahtlos zu löschen, ohne Flackern."
    },

    // --- 3. AKTIONEN BLOCK ---
    {
        "type": "lcd_keypad_action",
        "message0": "LCD Shield Aktion: %1",
        "args0": [
            {"type": "field_dropdown", "name": "ACTION", "options": [
                ["Display leeren (clear)", "clear()"],
                ["Cursor blinken EIN", "blink()"],
                ["Cursor blinken AUS", "noBlink()"],
                ["Cursor Linie EIN", "cursor()"],
                ["Cursor Linie AUS", "noCursor()"],
                ["Display Text EIN", "display()"],
                ["Display Text AUS", "noDisplay()"]
            ]}
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": LCD_KEYPAD_COLOR,
        "tooltip": "Führt spezielle LCD-Aktionen wie Löschen oder Blinken aus."
    },

    // --- 4. TASTER ABFRAGE ---
    {
        "type": "lcd_keypad_button",
        "message0": "LCD Shield Taster %1 %2",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "BUTTON",
                "options": [
                    ["Rechts (Right)", "1"],
                    ["Oben (Up)", "2"],
                    ["Unten (Down)", "3"],
                    ["Links (Left)", "4"],
                    ["Select (Enter)", "5"]
                ]
            },
            {
                "type": "field_dropdown",
                "name": "ACTION",
                "options": [
                    ["erkennt Einfachklick", "KK_SINGLE_CLICK"],
                    ["erkennt Doppelklick", "KK_DOUBLE_CLICK"],
                    ["erkennt langes Halten", "KK_LONG_PRESS"],
                    ["wird gerade gedrückt", "IS_PRESSED"],
                    ["wurde soeben losgelassen", "WAS_RELEASED"]
                ]
            }
        ],
        "output": "Boolean",
        "colour": 65, 
        "tooltip": "Wertet die Taster des LCD Shields am Pin A0 aus (inklusive Klick- und Halte-Events)."
    }
]);


// =======================================================================
// 2. C++ CODE GENERATOREN
// =======================================================================

// --- 1. SETUP GENERATOR ---
ArduinoGenerator.forBlock['lcd_keypad_setup'] = function(block) {
    const th_right = block.getFieldValue('TH_RIGHT');
    const th_up = block.getFieldValue('TH_UP');
    const th_down = block.getFieldValue('TH_DOWN');
    const th_left = block.getFieldValue('TH_LEFT');
    const th_select = block.getFieldValue('TH_SELECT');

    ArduinoGenerator.includes_.add('#include <LiquidCrystal.h>');
    ArduinoGenerator.globals_.add(`const int rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7;`);
    ArduinoGenerator.globals_.add(`LiquidCrystal lcd_shield(rs, en, d4, d5, d6, d7);`);
    
    ArduinoGenerator.globals_.add(`const int lk_lcd_thresh[5] = {${th_right}, ${th_up}, ${th_down}, ${th_left}, ${th_select}};`);

    ArduinoGenerator.globals_.add(`
class LcdKeypadHandler {
  private:
    unsigned long lastDebounceTime = 0;
    unsigned long buttonPressTime = 0;
    unsigned long lastClickTime = 0;
    int lastReading = 0;
    int currentBtn = 0;
    int lastPressedBtn = 0; 
    bool longPressFired = false;
    int eventCode = 0; 
    
    int readAnalogMap() {
      int adc_key_in = analogRead(A0);
      if (adc_key_in > 1000) return 0; 
      for(int i = 0; i < 5; i++) {
        if (adc_key_in < lk_lcd_thresh[i]) return i + 1;
      }
      return 0;
    }

  public:
    bool isPressed(int btn) { return (readAnalogMap() == btn); }
    
    void update() {
      eventCode = 0;
      int reading = readAnalogMap();
      unsigned long now = millis();
      
      if (reading != lastReading) {
        lastDebounceTime = now;
      }
      
      if ((now - lastDebounceTime) > 50) {
        if (reading != currentBtn) {
          if (reading != 0) { 
            buttonPressTime = now;
            longPressFired = false;
            lastPressedBtn = reading; 
          } else { 
            unsigned long pressDuration = now - buttonPressTime;
            if (pressDuration < 500 && !longPressFired) {
              if (now - lastClickTime < 300) {
                eventCode = 2; 
                lastClickTime = 0;
              } else {
                eventCode = 1; 
                lastClickTime = now;
              }
            }
          }
          currentBtn = reading;
        } else if (currentBtn != 0 && !longPressFired) {
          if (now - buttonPressTime > 800) {
            eventCode = 3; 
            longPressFired = true;
          }
        }
      }
      lastReading = reading;
    }

    int getEvent(int btn) {
      if (lastPressedBtn == btn) {
        return eventCode;
      }
      return 0;
    }
    
    bool wasReleased(int btn) {
       return (lastReading == 0 && currentBtn == 0 && eventCode > 0);
    }
};

LcdKeypadHandler lcdButtons;
    `);

    ArduinoGenerator.autoSetup_.push(`  lcd_shield.begin(16, 2);\n`);
    ArduinoGenerator.autoLoop_.unshift(`  lcdButtons.update();\n`);

    return '';
};

// --- 2a. SCHREIBEN GENERATOR (Normal) ---
ArduinoGenerator.forBlock['lcd_keypad_print'] = function(block) {
    const text = ArduinoGenerator.valueToCode(block, 'TEXT', 0) || '""';
    const row = ArduinoGenerator.valueToCode(block, 'ROW', 0) || '0';
    const col = ArduinoGenerator.valueToCode(block, 'COL', 0) || '0';
    
    return `  lcd_shield.setCursor(${col}, ${row});\n  lcd_shield.print(${text});\n`;
};

// --- 2b. ÜBERSCHREIBEN GENERATOR (Neu) ---
ArduinoGenerator.forBlock['lcd_keypad_print_overwrite'] = function(block) {
    const text = ArduinoGenerator.valueToCode(block, 'TEXT', 0) || '""';
    const row = ArduinoGenerator.valueToCode(block, 'ROW', 0) || '0';
    const col = ArduinoGenerator.valueToCode(block, 'COL', 0) || '0';
    
    let code = `  lcd_shield.setCursor(${col}, ${row});\n`;
    code += `  lcd_shield.print(${text});\n`;
    code += `  lcd_shield.print("    ");\n`; 
    return code;
};

// --- 3. AKTIONEN GENERATOR ---
ArduinoGenerator.forBlock['lcd_keypad_action'] = function(block) {
    const action = block.getFieldValue('ACTION'); 
    return `  lcd_shield.${action};\n`;
};

// --- 4. TASTER GENERATOR ---
ArduinoGenerator.forBlock['lcd_keypad_button'] = function(block) {
    const btn = block.getFieldValue('BUTTON');
    const action = block.getFieldValue('ACTION');
    
    if (action === "IS_PRESSED") {
        return [`lcdButtons.isPressed(${btn})`, 0];
    } else if (action === "WAS_RELEASED") {
        return [`lcdButtons.wasReleased(${btn})`, 0];
    } else {
        let targetEvent = 0;
        if (action === "KK_SINGLE_CLICK") targetEvent = 1;
        if (action === "KK_DOUBLE_CLICK") targetEvent = 2;
        if (action === "KK_LONG_PRESS") targetEvent = 3;
        
        return [`(lcdButtons.getEvent(${btn}) == ${targetEvent})`, 0];
    }
};