// =======================================================================
// ARDUINO LOGICKISTE: EXTERNE RTC MODULE (DS3231 / DS1307 via RTClib)
// =======================================================================

Blockly.defineBlocksWithJsonArray([
    // 1. SETUP
    {
        "type": "ard_rtc_ext_setup",
        "message0": "🕒 Setup Externe RTC %1",
        "args0": [
            {
                "type": "field_dropdown",
                "name": "RTC_TYPE",
                "options": [
                    ["DS3231 (Sehr genau)", "RTC_DS3231"],
                    ["DS1307 (Standard)", "RTC_DS1307"]
                ]
            }
        ],
        "previousStatement": null,
        "nextStatement": null,
        "colour": 120,
        "tooltip": "Initialisiert das externe I2C-Uhrenmodul. Benötigt die Adafruit RTClib."
    },

    // 2. LESEN
    {
        "type": "ard_rtc_ext_read",
        "message0": "Lese Externe RTC: %1",
        "args0": [
            { "type": "field_dropdown", "name": "PART", "options": [
                ["Stunde", "hour"],
                ["Minute", "minute"],
                ["Sekunde", "second"],
                ["Tag", "day"],
                ["Monat", "month"],
                ["Jahr", "year"],
                ["Wochentag (1-7)", "dow"]
            ]}
        ],
        "output": "Number",
        "colour": 160,
        "tooltip": "Liest den aktuellen Wert direkt live aus dem externen Modul aus."
    }
]);

// =======================================================================
// C++ GENERATOR & SCANNER
// =======================================================================

ArduinoGenerator.hardwareScanners['ard_rtc_ext_setup'] = function(block) {
    const rtcType = block.getFieldValue('RTC_TYPE');
    
    ArduinoGenerator.includes_.add('#include <Wire.h>');
    ArduinoGenerator.includes_.add('#include <RTClib.h>');
    
    // Globale Instanz erstellen (Name: extRTC)
    ArduinoGenerator.globals_.add(`${rtcType} extRTC;`);
    
    // Hilfsfunktion für den Wochentag (RTClib liefert 0=So, 1=Mo... LogicKiste nutzt 1=Mo... 7=So)
    ArduinoGenerator.globals_.add(`
int lk_getExtRTC(char part) {
  DateTime now = extRTC.now();
  switch(part) {
    case 'h': return now.hour();
    case 'm': return now.minute();
    case 's': return now.second();
    case 'D': return now.day();
    case 'M': return now.month();
    case 'Y': return now.year();
    case 'w': {
      int dow = now.dayOfTheWeek(); 
      return (dow == 0) ? 7 : dow; // Umrechnung auf 1=Mo, 7=So
    }
  }
  return 0;
}
`);
};

ArduinoGenerator.forBlock['ard_rtc_ext_setup'] = function(block) {
    let code = `  Wire.begin();\n`;
    code += `  if (!extRTC.begin()) {\n`;
    code += `    Serial.println("Externe RTC nicht gefunden!");\n`;
    code += `  }\n`;
    ArduinoGenerator.autoSetup_.push(code);
    return ''; 
};

ArduinoGenerator.forBlock['ard_rtc_ext_read'] = function(block) {
    const part = block.getFieldValue('PART');
    // Mappe Dropdown auf char für die C++ Funktion
    let charCode = 'h';
    if (part === 'hour') charCode = 'h';
    else if (part === 'minute') charCode = 'm';
    else if (part === 'second') charCode = 's';
    else if (part === 'day') charCode = 'D';
    else if (part === 'month') charCode = 'M';
    else if (part === 'year') charCode = 'Y';
    else if (part === 'dow') charCode = 'w';

    return [`lk_getExtRTC('${charCode}')`, 0];
};