// =======================================================================
// SIMULATION CORE: ZENTRALE KOMMUNIKATION (SPS ZYKLUS)
// =======================================================================

window.addSimCore = function(block) {
    // Variablen für Eingänge (10 Stück)
    ArduinoGenerator.globals_.add('int sim_in_0 = 0;\nint sim_in_1 = 0;\nint sim_in_2 = 0;\nint sim_in_3 = 0;\nint sim_in_4 = 0;\nint sim_in_5 = 0;\nint sim_in_a0 = 0;\nint sim_in_a1 = 0;');
    
    // Variablen für Ausgänge
    ArduinoGenerator.globals_.add('int sim_out_0 = 0;\nint sim_out_1 = 0;\nint sim_out_2 = 0;\nint sim_out_3 = 0;\nint sim_out_a0 = 0;\nint sim_out_a1 = 0;');
    
    // HMI Variablen und Timer
    ArduinoGenerator.globals_.add('String sim_hmi_l1 = "";\nString sim_hmi_l2 = "";');
    ArduinoGenerator.globals_.add('unsigned long kk_sim_last = 0;\nunsigned long kk_sim_zyklus = 100; // Einstellbare Zykluszeit');
    
    // Die zentrale Update-Funktion mit 10 Einlese-Werten!
    const updateFunc = `void kk_sim_update() {
  if (millis() - kk_sim_last >= kk_sim_zyklus) {
    kk_sim_last = millis();
    while (Serial.available() > 0) {
      String input = Serial.readStringUntil('\\n');
      input.trim();
      if (input.startsWith("IN:")) {
        input.remove(0, 3);
        int dummy_d6, dummy_d7;
        sscanf(input.c_str(), "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d", &sim_in_0, &sim_in_1, &sim_in_2, &sim_in_3, &sim_in_4, &sim_in_5, &dummy_d6, &dummy_d7, &sim_in_a0, &sim_in_a1);
      }
    }
    Serial.print("OUT:");
    Serial.print(sim_out_0); Serial.print(",");
    Serial.print(sim_out_1); Serial.print(",");
    Serial.print(sim_out_2); Serial.print(",");
    Serial.print(sim_out_3); Serial.print(",");
    Serial.print(sim_out_a0); Serial.print(",");
    Serial.println(sim_out_a1);
    
    if (sim_hmi_l1 != "") { Serial.println("L1:" + sim_hmi_l1); }
    if (sim_hmi_l2 != "") { Serial.println("L2:" + sim_hmi_l2); }
  }
}`;
    ArduinoGenerator.globals_.add(updateFunc);
    
    // Delay-Hack für blockierungsfreie Kommunikation
    ArduinoGenerator.globals_.add('#define delay(ms) { unsigned long _start_kk = millis(); while(millis() - _start_kk < (ms)) { kk_sim_update(); } }');

    // Serial Setup
    if (!ArduinoGenerator.autoSetup_.includes('  Serial.begin(115200);\n')) {
        ArduinoGenerator.autoSetup_.push('  Serial.begin(115200);\n');
    }

    // Update im Loop aufrufen
    const loopCall = `  kk_sim_update();\n`;
    if (!ArduinoGenerator.autoLoop_.includes(loopCall)) {
        ArduinoGenerator.autoLoop_.push(loopCall);
    }
};

// ---------------------------------------------------
// CONFIG: SPS ZYKLUSZEIT EINSTELLEN (Gehört am besten zum Core)
// ---------------------------------------------------
Blockly.defineBlocksWithJsonArray([{
  "type": "sim_config_zyklus",
  "message0": "⏱️ SPS Zykluszeit %1",
  "args0": [
    {
      "type": "field_dropdown",
      "name": "TIME",
      "options": [
        ["Schnell (20 ms)", "20"],
        ["Normal (100 ms)", "100"],
        ["Langsam (500 ms)", "500"],
        ["Extrem träge (1000 ms)", "1000"]
      ]
    }
  ],
  "previousStatement": null,
  "nextStatement": null,
  "colour": 20,
  "tooltip": "Legt fest, wie oft der Arduino mit der Simulation kommuniziert."
}]);

ArduinoGenerator.forBlock['sim_config_zyklus'] = function(block) {
    const time = block.getFieldValue('TIME');
    const setupCode = `  kk_sim_zyklus = ${time};\n`;
    if (!ArduinoGenerator.autoSetup_.includes(setupCode)) {
        ArduinoGenerator.autoSetup_.push(setupCode);
    }
    return '';
};