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

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

'use strict';

goog.require('Blockly.Arduino');

// ================================= I2C LCD ================================= //
var lcd_i2c_instance = 'lcd_i2c';

Blockly.Arduino['lcd_i2c_init'] = function(block) {
  const addr = block.getFieldValue('ADDR') || '0x27';
  const cols = Blockly.Arduino.valueToCode(block, 'COL', Blockly.Arduino.ORDER_ATOMIC) || '16';
  const rows = Blockly.Arduino.valueToCode(block, 'ROW', Blockly.Arduino.ORDER_ATOMIC) || '2';

  Blockly.Arduino.includes_['include_' + lcd_i2c_instance] = '#include <LiquidCrystal_I2C.h>';
  Blockly.Arduino.definitions_['def_' + lcd_i2c_instance] = 'LiquidCrystal_I2C '+ lcd_i2c_instance + '(' + addr + ', ' + cols + ', ' + rows +');';
  Blockly.Arduino.setups_['setup_' + lcd_i2c_instance] = lcd_i2c_instance + '.init();\n  ' + lcd_i2c_instance + '.backlight();';

  return '';
};

Blockly.Arduino['lcd_i2c_backlight'] = function(block) {
  const val = block.getFieldValue('VAL');

  var op = (val === 'ON') ? '.backlight' : '.noBacklight';
  var code = lcd_i2c_instance + op + '();\n'
  return code;
};

Blockly.Arduino['lcd_i2c_clear'] = function(block) {
  return lcd_i2c_instance + '.clear();\n';
};

Blockly.Arduino['lcd_i2c_print'] = function(block) {
  const text = Blockly.Arduino.valueToCode(block, 'TEXT', Blockly.Arduino.ORDER_ATOMIC) || '';
  // в библиотеке нумерация с 0, а в приложении с 1
  const col = Blockly.Arduino.valueToCode(block, 'COL', Blockly.Arduino.ORDER_ATOMIC) || '0';
  const row = Blockly.Arduino.valueToCode(block, 'ROW', Blockly.Arduino.ORDER_ATOMIC) || '0';

  var code = lcd_i2c_instance + '.setCursor(' + col + ' - 1, ' + row + ' - 1);\n'
  code += lcd_i2c_instance + '.print(' + text + ');\n'
  return code;
};