/**
 * @license
 * Copyright 2025 Elron
 * SPDX-License-Identifier: GPL3
 */

/**
 * @fileoverview Actuators blocks for Blockly.
 * @author info@elron.tech
 */

'use strict';

goog.provide('Blockly.Arduino.servo');

goog.require('Blockly.Arduino');

// ================================= Servo ================================= //
Blockly.Arduino['servo_move'] = function (block) {
    var pin = block.getFieldValue('PIN');
    var angle = Blockly.Arduino.valueToCode(block, 'ANGLE', Blockly.Arduino.ORDER_ATOMIC);
    var instance = 'servo_' + pin;

    Blockly.Arduino.includes_['include_servo'] = '#include <Servo.h>';
    Blockly.Arduino.definitions_['def_' + instance] = 'Servo ' + instance + ';';
    Blockly.Arduino.setups_['setup_' + instance] = instance + '.attach(' + pin + ');';

    var code = instance + '.write(' + angle + ');\n';
    return code;
};

Blockly.Arduino['stepper_init'] = function(block) {
  const motorNum = block.getFieldValue('NUM');
  const in1 = block.getFieldValue('IN1');
  const in2 = block.getFieldValue('IN2');
  const in3 = block.getFieldValue('IN3');
  const in4 = block.getFieldValue('IN4');
  const speed = Blockly.Arduino.valueToCode(block, 'SPEED', Blockly.Arduino.ORDER_ATOMIC) || '5';
  const instance = 'stepper_' + motorNum;

  Blockly.Arduino.includes_['stepper_include'] = '#include <Bonezegei_ULN2003_Stepper.h>';
  Blockly.Arduino.definitions_['def_' + instance] = 'Bonezegei_ULN2003_Stepper ' + instance + '(' + in1 + ', ' + in2 + ', ' + in3 + ', ' + in4 +');';
  var setups = instance + '.begin();';
  if (speed != '0'){
    setups += '\n  ' + instance + '.setSpeed(' + speed +');'
  }
  Blockly.Arduino.setups_['setup_' + instance] = setups;

  return '';
};

Blockly.Arduino['stepper_move'] = function(block) {
  const motorNum = block.getFieldValue('NUM');
  const direction = (block.getFieldValue('DIR') == "forw") ? "1" : "0";
  const mode = block.getFieldValue('MODE');
  const value = Blockly.Arduino.valueToCode(block, 'VALUE', Blockly.Arduino.ORDER_ATOMIC) || '0';
  const instance = 'stepper_' + motorNum;

  var func = ((mode === 'steps') ? ".step" : ".stepAngle");
  var code = instance + func + '(' + direction + ', ' + value + ');\n';
  return code;
};