// ==========================================
// KEYESTUDIO SHIELDS (KS0550 & KS0363)
// ==========================================

Blockly.defineBlocksWithJsonArray([
  // --- 1. SERVO / SENSOR PORT (Für beide Shields) ---
  {
    "type": "ks_shield_servo",
    "message0": "Shield Port %1 auf Winkel %2 °",
    "args0": [
      {
        "type": "field_dropdown",
        "name": "PIN",
        "options": [
          // Hier die EXAKTEN 10 Ports eintragen, die das Shield hat!
          ["S1 (D2)", "2"],
          ["S2 (D3)", "3"],
          ["S3 (D4)", "4"],
          ["S4 (D5)", "5"],
          ["S5 (D8)", "8"],
          ["S6 (D9)", "9"],
          ["S7 (D10)", "10"],
          ["S8 (D11)", "11"],
          ["S9 (A0)", "A0"],
          ["S10 (A1)", "A1"]
        ]
      },
      {
        "type": "input_value",
        "name": "DEGREE",
        "check": "Number"
      }
    ],
    "previousStatement": null,
    "nextStatement": null,
    "colour": 180,
    "tooltip": "Steuert einen Servo an den verfügbaren Shield-Ports."
  },

  // --- 2. DC MOTOR (KS0363 Shield) ---
  {
    "type": "ks0363_motor",
    "message0": "KS0363 Motor %1 Richtung %2 Tempo %3",
    "args0": [
      {
        "type": "field_dropdown",
        "name": "MOTOR",
        "options": [
          ["Motor A", "A"],
          ["Motor B", "B"]
        ]
      },
      {
        "type": "field_dropdown",
        "name": "DIR",
        "options": [
          ["Vorwärts", "FWD"],
          ["Rückwärts", "REV"],
          ["Stopp", "STOP"]
        ]
      },
      {
        "type": "input_value",
        "name": "SPEED",
        "check": "Number"
      }
    ],
    "previousStatement": null,
    "nextStatement": null,
    "colour": 180,
    "tooltip": "Steuert die TB6612FNG Motoren auf dem KS0363 Shield."
  },

  // --- 3. PS2 GAMEPAD SETUP ---
  {
    "type": "ks_shield_ps2_setup",
    "message0": "PS2 Gamepad am Shield initialisieren",
    "previousStatement": null,
    "nextStatement": null,
    "colour": 45,
    "tooltip": "Startet die Kommunikation mit dem PS2 Empfänger auf dem Shield."
  },

  // --- 4. PS2 GAMEPAD ABFRAGE ---
  {
    "type": "ks_shield_ps2_button",
    "message0": "PS2 Taste %1 gedrückt?",
    "args0": [
      {
        "type": "field_dropdown",
        "name": "BUTTON",
        "options": [
          ["Kreuz (Grün)", "PSB_CROSS"],
          ["Kreis (Rot)", "PSB_CIRCLE"],
          ["Viereck (Pink)", "PSB_SQUARE"],
          ["Dreieck (Blau)", "PSB_TRIANGLE"],
          ["Pfeil Oben", "PSB_PAD_UP"],
          ["Pfeil Unten", "PSB_PAD_DOWN"],
          ["Pfeil Links", "PSB_PAD_LEFT"],
          ["Pfeil Rechts", "PSB_PAD_RIGHT"],
          ["L1", "PSB_L1"],
          ["R1", "PSB_R1"],
          ["Select", "PSB_SELECT"],
          ["Start", "PSB_START"]
        ]
      }
    ],
    "output": "Boolean",
    "colour": 45,
    "tooltip": "Gibt wahr zurück, wenn die Taste auf dem PS2 Controller gedrückt wird."
  }
]);


// ==========================================
// 1. SERVO GENERATOR (Für beide Shields)
// ==========================================
ArduinoGenerator.hardwareScanners['ks_shield_servo'] = function(block) {
    ArduinoGenerator.globals_.add(`#include <Servo.h>`);
    const pin = block.getFieldValue('PIN');
    ArduinoGenerator.globals_.add(`Servo shieldServo_${pin};`);
};

ArduinoGenerator.forBlock['ks_shield_servo'] = function(block) {
    const pin = block.getFieldValue('PIN');
    const degree = ArduinoGenerator.valueToCode(block, 'DEGREE', 0) || '0';
    
    ArduinoGenerator.autoSetup_.push(`  shieldServo_${pin}.attach(pin${pin});\n`);
    ArduinoGenerator.usedPinsOutput.add(pin);
    
    return `  shieldServo_${pin}.write(${degree});\n`;
};


// ==========================================
// 2. DC MOTOR GENERATOR (KS0363)
// ==========================================
ArduinoGenerator.hardwareScanners['ks0363_motor'] = function(block) {
    // ACHTUNG: Hier ggf. die echten Pins des KS0363 für den TB6612FNG anpassen,
    // falls sie im Datenblatt abweichen!
    ArduinoGenerator.globals_.add(`// --- KS0363 Motor Pins ---`);
    ArduinoGenerator.globals_.add(`const int KS0363_PWMA = 5;`);
    ArduinoGenerator.globals_.add(`const int KS0363_AIN1 = 6;`);
    ArduinoGenerator.globals_.add(`const int KS0363_AIN2 = 7;`);
    ArduinoGenerator.globals_.add(`const int KS0363_PWMB = 9;`);
    ArduinoGenerator.globals_.add(`const int KS0363_BIN1 = 10;`);
    ArduinoGenerator.globals_.add(`const int KS0363_BIN2 = 11;`);
};

ArduinoGenerator.forBlock['ks0363_motor'] = function(block) {
    const motor = block.getFieldValue('MOTOR');
    const dir = block.getFieldValue('DIR');
    const speed = ArduinoGenerator.valueToCode(block, 'SPEED', 0) || '0';
    
    const pwmPin = motor === 'A' ? 'KS0363_PWMA' : 'KS0363_PWMB';
    const in1Pin = motor === 'A' ? 'KS0363_AIN1' : 'KS0363_BIN1';
    const in2Pin = motor === 'A' ? 'KS0363_AIN2' : 'KS0363_BIN2';
    
    // Pins als Ausgang definieren
    ArduinoGenerator.usedPinsOutput.add(pwmPin.replace('KS0363_', ''));
    ArduinoGenerator.usedPinsOutput.add(in1Pin.replace('KS0363_', ''));
    ArduinoGenerator.usedPinsOutput.add(in2Pin.replace('KS0363_', ''));
    
    let code = ``;
    
    if (dir === 'STOP') {
        code += `  digitalWrite(${in1Pin}, LOW);\n`;
        code += `  digitalWrite(${in2Pin}, LOW);\n`;
        code += `  analogWrite(${pwmPin}, 0);\n`;
    } else if (dir === 'FWD') {
        code += `  digitalWrite(${in1Pin}, HIGH);\n`;
        code += `  digitalWrite(${in2Pin}, LOW);\n`;
        code += `  analogWrite(${pwmPin}, ${speed});\n`;
    } else if (dir === 'REV') {
        code += `  digitalWrite(${in1Pin}, LOW);\n`;
        code += `  digitalWrite(${in2Pin}, HIGH);\n`;
        code += `  analogWrite(${pwmPin}, ${speed});\n`;
    }
    
    return code;
};


// ==========================================
// 3. PS2 GAMEPAD SETUP
// ==========================================
ArduinoGenerator.hardwareScanners['ks_shield_ps2_setup'] = function(block) {
    ArduinoGenerator.globals_.add(`#include <PS2X_lib.h>`);
    ArduinoGenerator.globals_.add(`PS2X ps2x;`);
    
    // Auch hier: Passe die Pins an die feste 9-Pin-Buchse des Shields an, falls abweichend!
    ArduinoGenerator.globals_.add(`const int PS2_DAT = 12;`);
    ArduinoGenerator.globals_.add(`const int PS2_CMD = 11;`);
    ArduinoGenerator.globals_.add(`const int PS2_SEL = 10;`);
    ArduinoGenerator.globals_.add(`const int PS2_CLK = 13;`);
};

ArduinoGenerator.forBlock['ks_shield_ps2_setup'] = function(block) {
    // Initialisierung des PS2-Controllers. Parameter: Clock, Command, Attention, Data
    ArduinoGenerator.autoSetup_.push(`  ps2x.config_gamepad(PS2_CLK, PS2_CMD, PS2_SEL, PS2_DAT, false, false);\n`);
    
    // Controller muss im Loop immer mal wieder gelesen werden, damit Buttons erkannt werden
    return `  ps2x.read_gamepad(false, 0); // Controller updaten\n`;
};


// ==========================================
// 4. PS2 GAMEPAD BUTTON ABFRAGE
// ==========================================
ArduinoGenerator.forBlock['ks_shield_ps2_button'] = function(block) {
    const button = block.getFieldValue('BUTTON');
    const code = `ps2x.Button(${button})`;
    
    return [code, 0];
};