/* eslint-disable no-unused-expressions */
import * as Blockly from 'blockly';
import { pythonGenerator } from 'blockly/python';
import { getBlocksByTypeName } from "../../utils/blocklyFunction"

Blockly.Python = pythonGenerator || { Msg: Object.create(null) };
// 基础
const basicColor = "#d42b03";
Blockly.Blocks['ai_v831_button_read_pressed'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_button_when)
            .appendField(new Blockly.FieldDropdown([
                ["A", "A"],
                ["B", "B"],
                ["C", "C"],
                ["D", "D"]
            ]), "button_type")
            .appendField(Blockly.Msg.ai_basic_pressed)
        this.setOutput(true, null);
        this.setColour(basicColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('button_type');
            console.log(mode)
            var TOOLTIPS = {
                'A': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "A"),
                'B': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "B"),
                'C': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "C"),
                'D': Blockly.Msg.ai_k210_button_read_pressed_TOOLTIP.replace('%1', "D"),
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_button_read_pressed'] = function (block) {
    var _type = block.getFieldValue('button_type');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
    // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
    Blockly.Python.definitions_['import_define_x_button'] = `key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)
`

    var code = `key_${_type}.is_pressed()`
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['ai_v831_button_read_released'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_button_when)
            .appendField(new Blockly.FieldDropdown([
                ["A", "A"],
                ["B", "B"],
                ["C", "C"],
                ["D", "D"]
            ]), "button_type_released")
            .appendField(Blockly.Msg.ai_basic_released)
        this.setOutput(true, null);
        this.setColour("#d42b03");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('button_type_released');
            var TOOLTIPS = {
                'A': Blockly.Msg.ai_k210_button_read_released_TOOLTIP.replace('%1', "A"),
                'B': Blockly.Msg.ai_k210_button_read_released_TOOLTIP.replace('%1', "B"),
                'C': Blockly.Msg.ai_k210_button_read_released_TOOLTIP.replace('%1', "C"),
                'D': Blockly.Msg.ai_k210_button_read_released_TOOLTIP.replace('%1', "D"),
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_button_read_released'] = function (block) {
    var _type = block.getFieldValue('button_type_released');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_CocoPi_BUTTON'] = `from CocoPi import BUTTON`
    // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
    Blockly.Python.definitions_['import_define_x_button'] = `key_A = BUTTON(14)
key_B = BUTTON(8)
key_C = BUTTON(13)
key_D = BUTTON(7)
`

    var code = `key_${_type}.is_pressed() == False`
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};
Blockly.Blocks['ai_v831_led_light_up'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_led_set)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.ai_basic_led_blue, "blue"],
                // [Blockly.Msg.ai_basic_led_red, "red"]
            ]), "type")
            .appendField(Blockly.Msg.ai_basic_led_on);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#d42b03");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('type');
            var TOOLTIPS = {
                'blue': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
                'red': Blockly.Msg.ai_k210_led_light_up_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_led_light_up'] = function (block) {
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_CocoPi_LED'] = `from CocoPi import LED
LED = LED()
`
    // TODO: Assemble Python into code variable.
    var code = `LED.out(1)
`;
    return code;
};

Blockly.Blocks['ai_v831_led_light_off'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_led_set)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.ai_basic_led_blue, "blue"],
                // [Blockly.Msg.ai_basic_led_red, "red"]
            ]), "type")
            .appendField(Blockly.Msg.ai_basic_led_off);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#d42b03");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('type');
            var TOOLTIPS = {
                'blue': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_blue),
                'red': Blockly.Msg.ai_k210_led_light_off_TOOLTIP.replace('%1', Blockly.Msg.ai_basic_led_red)
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_led_light_off'] = function (block) {
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_CocoPi_LED'] = `from CocoPi import LED
LED = LED()
`
    // TODO: Assemble Python into code variable.
    var code = `LED.out(0)
`;
    return code;
};

Blockly.Blocks['ai_v831_rgb_light_up'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_rgb_set_on)
        this.appendValueInput("rgb_value")
            .setCheck(null)
            .appendField("");
        this.appendDummyInput()
            .appendField(Blockly.Msg.LED_BRTN).appendField(new Blockly.FieldNumber(50, 0, 255), "uart_bps");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#d42b03");
        this.setTooltip(Blockly.Msg.ai_basic_rgb_set_on);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_rgb_light_up'] = function (block) {
    var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
    var content = block.getFieldValue('uart_bps');
    console.log(value_name.slice(1, -1))
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_CocoPi_RGB'] = `from CocoPi import singleRgb
singleRgb=singleRgb()`;

    var code = `singleRgb.setBrightness(${content})
singleRgb.setColor(${value_name.slice(1, -1)})
singleRgb.show()
time.sleep(0.05)
`;
    return code;
};

Blockly.Blocks['ai_v831_rgb_light_off'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ai_basic_rgb_set_off)
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#d42b03");
        this.setTooltip(Blockly.Msg.ai_basic_rgb_set_off);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_v831_rgb_light_off'] = function (block) {
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_CocoPi_RGB'] = `from CocoPi import singleRgb
singleRgb=singleRgb()`;

    // TODO: Assemble Python into code variable.
    var code = `singleRgb.setColor(0,0,0)
singleRgb.show()
time.sleep(0.05)
`;
    return code;
};

Blockly.Blocks['ai_lcd_rgb_value_input'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_R);
        this.appendValueInput("rgb_value_r")
            .setCheck(null)
            .appendField("");
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_G);
        this.appendValueInput("rgb_value_g")
            .setCheck(null)
            .appendField("");
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_B);
        this.appendValueInput("rgb_value_b")
            .setCheck(null)
            .appendField("");
        this.setInputsInline(true);
        this.setOutput(true, null);
        this.setColour("#5bb2d6");
        this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_lcd_rgb_value_input'] = function (block) {
    var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
    var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
    var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
    // TODO: Assemble Python into code variable.
    var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + '';
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_NONE];
};


const SensorsColor = "#5fcd8e";
Blockly.Blocks['esp32_main_controller_get_light'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.basic_light_get);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(SensorsColor);
        this.setTooltip(Blockly.Msg.basic_light_get);
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_main_controller_get_light'] = function (block) {
    Blockly.Python.definitions_['import_LIGHTINTENSITY'] = `class v83x_ADC():
    def __init__(self, addr=b"0x05070080") -> None:
        self.addr = addr
        self.path = "/sys/class/sunxi_dump/dump"
        self.file = open(self.path, "wb+")
        self.last = self.value()
    def __del__(self):
        try:
            if self.file:
                self.file.close()
                del self.file
        except Exception as e:
            pass
    def value(self):
        self.file.write(b"0x05070080")
        self.file.seek(0)
        return int(self.file.read()[:-1], 16)

v831_adc0 = v83x_ADC()
`
    var code = 'v831_adc0.value()';
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_get_environmental_value'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ESP32_ENV_GET_TEXT)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.basic_temperature, "temperature"],
                [Blockly.Msg.basic_humidity, "humidity"]
            ]), "env_get_type")
            .appendField(Blockly.Msg.basic_env_value);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(SensorsColor);
        this.setHelpUrl("");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('env_get_type');
            var TOOLTIPS = {
                'temperature': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_temperature),
                'humidity': Blockly.Msg.Esp32_Main_Controller_Get_Environmental_Value_TOOLTIP.replace('%1', Blockly.Msg.basic_humidity)
            };
            return TOOLTIPS[mode];
        });
    }
};

Blockly.Python['esp32_main_controller_get_environmental_value'] = function (block) {
    var _type_selected = block.getFieldValue('env_get_type');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_AHT20'] = `from CocoPi import AHT20`
    // Blockly.Python.definitions_['v831_import_CocoPi'] = `sys.path.append("/root/")`
    Blockly.Python.definitions_['import_AHT20_object'] = `aht20 = AHT20(2)`

    let code = ''
    if (_type_selected == 'temperature') {
        code = `aht20.get_temperature()`
    } else if (_type_selected == 'humidity') {
        code = `aht20.get_humidity()`;
    } else {
        code = _type_selected;
    }
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_acceleration'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.basic_motion_get_along)
            .appendField(new Blockly.FieldDropdown([
                ["X", "4"],
                ["Y", "3"],
                ["Z", "5"]
            ]), "accel_type")
            .appendField(Blockly.Msg.basic_motion_accel);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(SensorsColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('accel_type');
            var TOOLTIPS = {
                '4': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'X'),
                '3': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Y'),
                '5': Blockly.Msg.Esp32_Main_Controller_Motion_Acceleration_TOOLTIP.replace('%1', 'Z')
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_main_controller_motion_acceleration'] = function (block) {
    var _type_selected = block.getFieldValue('accel_type');
    // var is_unit = block.getFieldValue('isUnit');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_QMI8658'] = `from CocoPi import QMI8658`
    Blockly.Python.definitions_['QMI8658_import_path'] = `
#初始化设置
qmi8658=QMI8658()
#校准
qmi8658.calibrate()
#标定初始方位
initData={}
initData["AcX"]=qmi8658.get_accel(10)["AcX"]
initData["AcY"]=qmi8658.get_accel(10)["AcY"]
initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
initData["GyX"]=qmi8658.get_accel(10)["GyX"]
initData["GyY"]=qmi8658.get_accel(10)["GyY"]
initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
`;


    var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`;
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_rotation_measurement'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.basic_motion_get_along)
            .appendField(new Blockly.FieldDropdown([
                ["X", "4"],
                ["Y", "3"],
                ["Z", "5"]
            ]), "accel_type")
            .appendField(Blockly.Msg.basic_motion_rotation_measurement);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(SensorsColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('accel_type');
            var TOOLTIPS = {
                '4': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'X'),
                '3': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'Y'),
                '5': Blockly.Msg.Esp32_Main_Controller_Motion_Rotation_Measurement_TOOLTIP.replace('%1', 'Z')
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_main_controller_motion_rotation_measurement'] = function (block) {
    var _type_selected = block.getFieldValue('accel_type');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_QMI8658'] = `from CocoPi import QMI8658`
    Blockly.Python.definitions_['QMI8658_import_path'] = `
#初始化设置
qmi8658=QMI8658()
#校准
qmi8658.calibrate()
#标定初始方位
initData={}
initData["AcX"]=qmi8658.get_accel(10)["AcX"]
initData["AcY"]=qmi8658.get_accel(10)["AcY"]
initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
initData["GyX"]=qmi8658.get_accel(10)["GyX"]
initData["GyY"]=qmi8658.get_accel(10)["GyY"]
initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
`;
    var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`;
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['esp32_main_controller_motion_tilt_angle'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.basic_motion_get_along)
            .appendField(new Blockly.FieldDropdown([
                ["X", "1"],
                ["Y", "0"],
                // ["Z", "2"]
            ]), "tilt_angle_type")
            .appendField(Blockly.Msg.basic_motion_angle);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(SensorsColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('tilt_angle_type');
            var TOOLTIPS = {
                '1': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'X'),
                '0': Blockly.Msg.Esp32_Main_Controller_Motion_Tilt_Angle_TOOLTIP.replace('%1', 'Y')
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl("");
    }
};


Blockly.Python['esp32_main_controller_motion_tilt_angle'] = function (block) {
    var _type_selected = block.getFieldValue('tilt_angle_type');
    // var is_unit = block.getFieldValue('isUnit');
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_QMI8658'] = `from CocoPi import QMI8658`
    Blockly.Python.definitions_['QMI8658_import_path'] = `
#初始化设置
qmi8658=QMI8658()
#校准
qmi8658.calibrate()
#标定初始方位
initData={}
initData["AcX"]=qmi8658.get_accel(10)["AcX"]
initData["AcY"]=qmi8658.get_accel(10)["AcY"]
initData["AcZ"]=qmi8658.get_accel(10)["AcZ"]
initData["GyX"]=qmi8658.get_accel(10)["GyX"]
initData["GyY"]=qmi8658.get_accel(10)["GyY"]
initData["GyZ"]=qmi8658.get_accel(10)["GyZ"]
`
    var code = `round(qmi8658.getPitchYawRollGxGyGz(initData)[${_type_selected}],2)`
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};

// 动力
const servoColor = "#386dc8";
Blockly.Blocks['extension_servo_setup_on_ai'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("/media/esp32_servo_setup.png", 50, 40, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.servo_setup_ai);
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(servoColor);
        this.setTooltip(Blockly.Msg.extension_servo_setup_on_ai_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['extension_servo_setup_on_ai'] = function (block) {
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    Blockly.Python.definitions_['import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;
    //     Blockly.Python.definitions_["v831_set_servo_S1_S2"] = `S1= multiFuncGpio(0,1)
    // S2= multiFuncGpio(1,1)`
    Blockly.Python.definitions_['import_CocoPi_multiFuncGpio'] = `from CocoPi import multiFuncGpio`;

    try {
        const allBlocks = getBlocksByTypeName("extension_servo_write_on_ai")
        let onedegree = allBlocks.length > 0 ? allBlocks[0].textContent : "";
        if (onedegree.indexOf("S1") != -1) {
            let degree = 0
            for (let i = 0; i < allBlocks.length; i++) {
                if (allBlocks[i].textContent.indexOf("S1") == 0) {
                    degree = allBlocks[i].children[1].textContent;
                    break;
                }
            }
            Blockly.Python.definitions_["servo_initS1"] = `S1= multiFuncGpio(0,1)
S1.servoCtrl(${isNaN(Number(degree)) ? 90 : degree})`
        }
        if (onedegree.indexOf("S2") != -1) {
            let degree1 = 0
            for (let i = 0; i < allBlocks.length; i++) {
                if (allBlocks[i].textContent.indexOf("S2") == 0) {
                    degree1 = allBlocks[i].children[1].textContent;
                    break;
                }
            }
            Blockly.Python.definitions_["servo_initS2"] = `S2= multiFuncGpio(1,1)
S2.servoCtrl(${isNaN(Number(degree1)) ? 90 : degree1})`
        }
    } catch (e) {
        console.log("error", e)
    }
    var code = '';
    return code;
};


Blockly.Blocks['extension_servo_write_on_ai'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.servo_set_gpio_ai)
            .appendField(new Blockly.FieldDropdown([
                ["S1", "S1"],
                ["S2", "S2"],
                ["P0", "P0"],
                ["P1", "P1"],
                ["P2", "P2"],
                ["P3", "P3"]
            ]), "gpio");
        this.appendValueInput("degree")
            .setCheck(null)
            .appendField(Blockly.Msg.servo_rotate_to_ai);
        this.appendDummyInput()
            .appendField(Blockly.Msg.servo_degree_ai);
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(servoColor);
        this.setTooltip(Blockly.Msg.extension_servo_write_on_ai_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['extension_servo_write_on_ai'] = function (block) {
    var value_degree = Blockly.Python.valueToCode(block, 'degree', Blockly.Python.ORDER_ATOMIC);
    var value_gpio = block.getFieldValue('gpio');
    let code = ""
    // console.log('1. ',performance.now())
    if (value_gpio == "S1" || value_gpio == "S2") {
        code = `${value_gpio}.servoCtrl(${value_degree})\n`
    } else {
        Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
        Blockly.Python.definitions_['import_CocoPi_extServo'] = `
class PCA9685(object):
    bus=smbus2.SMBus(2)
    def __init__(self,freq=400,min_us=460,max_us=2400,address=0x40,degrees=180):
        self.address=address
        self.period=1000000/freq
        self.min_duty = self._us2duty(min_us)
        self.max_duty = self._us2duty(max_us)
        self.freq(freq)
        self.reset()
        #for i in range(0,16):
            #self.duty(i,0)
        print("Pca9685 init")
        
    def write(self, addr, val):
        for i in range(0, 2):
            try:
                self.bus.write_byte_data(self.address, addr, val)
                #time.sleep(0.001) # 1ms
                # print(addr, val) # debug
                return True
            except Exception:
                time.sleep(0.001)
                continue
        return False
        
    def read(self,addr):
        for i in range(0, 3):
            try:
                tmp = self.bus.read_byte_data(self.address, addr)
                #time.sleep(0.001) # 1ms
                # print(addr, tmp) # debug
                return tmp
            except Exception:
                time.sleep(0.01)
                continue
        return None
    
    def reset(self):
        self.write(0x00,0x00)        #初始化
    
    def freq(self,freq=None):
        if freq is None:
            return int(25000000.0/4096/(self.read(0xfe)-0.5))
        #设定频率freq,预分频prescale=int(25000000.0 / (4096.0 * freq) + 0.5)
        prescale=int(25000000.0/4096/freq+0.5)
        self.write(0x00,0x10)        #设定pca9685为睡眠模式
        self.write(0xfe,prescale)    #设定频率
        self.reset()
        time.sleep(0.01)
        self.write(0x00,0xa1)        #设定pca9685为活跃模式
    
    def pwm(self,index,on=None,off=None):            #on和off来调节PWM的占空比
        if not 0<= index <=15:
            raise ValueError("Pin ID out of range!")
        if on is None or off is None:
            data = self.bus.read_i2c_block_data(self.address,0x06+index*4,4)
            return data
        data= [0]*4
        data[0]=int(hex(on & 0xff),16)
        data[1]=int(hex((on >> 8) & 0xff),16)
        data[2]=int(hex(off & 0xff),16)
        data[3]=int(hex((off >> 8) & 0xff),16)
        # print(data)
        for i in range(0,4):
            self.write(0x06+i+index*4,data[i])
        
    def duty(self,index,value=None):
        if value == None:
            return self.pwm(index)
        elif not 0 <= value <=4095:
            raise ValueError("Out of range!")
        elif value==0:
            self.pwm(index,0,4096)
        elif value == 4095:
            self.pwm(index,4096,0)
        else:
            self.pwm(index,0,value)  

    def _us2duty(self,value):
        return 4095*value/self.period
        
    def __del__(self):
        print("del pac9685")
        time.sleep(1)
        for i in range(0,16):
            self.duty(i,0)
        time.sleep(0.001)
    
class extServo(PCA9685):
    def __init__(self,servoId):
        PCA9685.__init__(self)
        self.servoId=servoId
        self.servoPin=[14,15,1,0]
        self.degrees=180
        pass      
        
    def position(self,degrees=None):        #index:0,1,2,3
        if degrees == 180:
            self.max_duty = 3800
        span = self.max_duty - self.min_duty
        duty = self.min_duty + span * degrees / self.degrees
        duty = int(min(self.max_duty, max(self.min_duty, int(duty))))
        self.duty(self.servoPin[self.servoId], duty)
        
    def release(self):
        self.duty(self.servoPin[self.servoId],0)
    
    def __del__(self):  
        self.duty(self.servoPin[self.servoId],0)
 `;
        Blockly.Python.definitions_["servo_init_" + value_gpio] = `${value_gpio} = extServo(${value_gpio[1]})`
        code = `${value_gpio}.position(${value_degree})\n`
    }
    return code;
};
Blockly.Blocks['ai_motor_setup'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("/media/motor_setup.png", 50, 40, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.x_motor_set_motor_ai)
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(servoColor);
        this.setTooltip(Blockly.Msg.ai_motor_setup_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_motor_setup'] = function (block) {
    // TODO: Assemble Python into code variable.
    Blockly.Python.definitions_['import_smbus2'] = `import smbus2`
    Blockly.Python.definitions_['import_time'] = `import time`
    Blockly.Python.definitions_['import_sys'] = `import sys
sys.path.append("/root/")`
    //     Blockly.Python.definitions_["v831_motor_init"] = `M1=dcMotor(1)
    // M2=dcMotor(2)`

    var code = '';
    return code;
};
Blockly.Blocks['ai_motor_run'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.x_motor_set_motor_turn_ai)
            .appendField(new Blockly.FieldDropdown([
                ["M1", "M1"],
                ["M2", "M2"],
                ["M3", "C"],
                ["M4", "D"],
                ["M5", "E"],
                ["M6", "F"]
            ]), "motor_type")
            .appendField(Blockly.Msg.x_motor_set_motor_speed_ai);
        this.appendValueInput("speed")
            .setCheck(null);
        this.appendDummyInput()
            .appendField(Blockly.Msg.x_motor_exec_ai)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.x_motor_cw_ai, "pos"],
                [Blockly.Msg.x_motor_acw_ai, "neg"]
            ]), "direction")
            .appendField(Blockly.Msg.x_motor_set_motor_turns_ai);
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(servoColor);
        this.setTooltip(Blockly.Msg.ai_motor_run_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_motor_run'] = function (block) {
    var dropdown_motor_type = block.getFieldValue('motor_type');
    var value_speed = Blockly.Python.valueToCode(block, 'speed', Blockly.Python.ORDER_ATOMIC);
    var dropdown_direction = block.getFieldValue('direction');
    var code = ''
    if (dropdown_motor_type === "M1" || dropdown_motor_type === "M2") {
        Blockly.Python.definitions_['import_CocoPi_stm8s_init'] = `from CocoPi import stm8s
iic_slaver=stm8s()
iic_slaver.clear()
del iic_slaver`;
        Blockly.Python.definitions_['import_CocoPi_stm8s'] = `from CocoPi import dcMotor`;
        Blockly.Python.definitions_["dcMotorCtrlFun" + dropdown_motor_type] = `${dropdown_motor_type} = dcMotor(${dropdown_motor_type.slice(1, 2)})`
        if (dropdown_direction == 'pos') {
            code = `${dropdown_motor_type}.dcMotorCtrl(1,${value_speed})\n`
        }
        else {
            code = `${dropdown_motor_type}.dcMotorCtrl(0,${value_speed})\n`
        }
    } else {
        Blockly.Python.definitions_['import_CocoPi_extDcMotor'] = `from CocoPi import extDcMotor`;
        Blockly.Python.definitions_["dcMotorCtrlFun" + dropdown_motor_type] = `${dropdown_motor_type} = extDcMotor("${dropdown_motor_type}")`
        if (dropdown_direction == 'pos') {
            code = `${dropdown_motor_type}.speedControl(${value_speed})\n`
        }
        else {
            code = `${dropdown_motor_type}.speedControl(-${value_speed})\n`
        }
    }
    return code;
};

// 屏幕

const screenColor = "#5cb2d6";
Blockly.Blocks["ai_lcd_screeninit"] = {
    init: function () {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("/media/screen_init_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_lcd_init);
        this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_direction)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.image_process_lcd_landscape_screen, "False"],
                [Blockly.Msg.image_process_lcd_vertical_screen, "True"]
            ]), "isScreen")
        this.setInputsInline(false);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_screeninit_TOOLTIP);
        this.setHelpUrl('');
    }
}

Blockly.Python.ai_lcd_screeninit = function (block) {
    var isScreen = block.getFieldValue('isScreen');
    Blockly.Python.definitions_['import_display'] = `from maix import display`;
    Blockly.Python.definitions_['import_image'] = `from maix import image`;
    Blockly.Python.definitions_['import_camera'] = `from maix import camera`;
    Blockly.Python.definitions_['import_os'] = `import os`
    return _code;;
}
Blockly.Blocks['ai_lcd_rgb_value_input'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_R);
        this.appendValueInput("rgb_value_r")
            .setCheck(null)
            .appendField("");
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_G);
        this.appendValueInput("rgb_value_g")
            .setCheck(null)
            .appendField("");
        this.appendDummyInput()
            .appendField(Blockly.Msg.rgb_B);
        this.appendValueInput("rgb_value_b")
            .setCheck(null)
            .appendField("");
        this.setInputsInline(true);
        this.setOutput(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_rgb_value_input_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_lcd_rgb_value_input'] = function (block) {
    var value_rgb_value_r = Blockly.Python.valueToCode(block, 'rgb_value_r', Blockly.Python.ORDER_ATOMIC);
    var value_rgb_value_g = Blockly.Python.valueToCode(block, 'rgb_value_g', Blockly.Python.ORDER_ATOMIC);
    var value_rgb_value_b = Blockly.Python.valueToCode(block, 'rgb_value_b', Blockly.Python.ORDER_ATOMIC);
    var code = '' + value_rgb_value_r + ',' + value_rgb_value_g + ',' + value_rgb_value_b + '';
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks.ai_lcd_XY = {
    init: function () {
        var _input = this.appendDummyInput();
        this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
        this.setTooltip(Blockly.Msg.ai_lcd_XY_TOOLTIP);
        this.setColour(screenColor);
        this.setOutput(!0, "Boolean");
        _input.appendField(Blockly.Msg.image_process_xy_x);
        this.appendValueInput("A").setCheck("Number");
        _input = this.appendDummyInput();
        _input.appendField(Blockly.Msg.image_process_xy_y)
        this.appendValueInput("B").setCheck("Number");
        this.setInputsInline(!0);
    }
};

Blockly.Python.ai_lcd_XY = function (block) {
    var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);
    var _y = Blockly.Python.valueToCode(block, "B", Blockly.Python.ORDER_ATOMIC);
    var code = "" + _x + ", " + _y + "";
    return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Blocks['lcd_set_width_height'] = {
    init: function () {
        this.appendValueInput("WIDTH")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_wh_width);
        this.appendValueInput("HEIGHT")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_wh_height);
        this.setOutput(true, "String");
        this.setInputsInline(true);
        this.setColour(screenColor);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python['lcd_set_width_height'] = function (block) {
    var width = Blockly.Python.valueToCode(block, 'WIDTH', Blockly.Python.ORDER_ATOMIC);
    var height = Blockly.Python.valueToCode(block, 'HEIGHT', Blockly.Python.ORDER_ATOMIC);
    var code = width + ', ' + height;
    return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Blocks['ai_lcd_font'] = {
    init: function () {
        this.appendDummyInput().appendField(Blockly.Msg.image_lcd_set_font)
        this.appendValueInput("save_path")
            .setCheck(null)
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.image_lcd_set_font);
        this.setHelpUrl('');
    }
}

Blockly.Python.ai_lcd_font = function (block) {
    var font_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['ai_lcd_font'] = `image.load_freetype(${font_path})
`
    var _code = "";
    return _code;;
}
Blockly.Blocks["ai_lcd_createnonecarvas"] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_create_blank_canvas)
            ;
        this.appendValueInput("wh")
            .setCheck(null)
            .appendField(Blockly.Msg.image_process_text_size);
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_createnonecarvas_TOOLTIP);
        this.setHelpUrl('');
    }
}

Blockly.Python.ai_lcd_createnonecarvas = function (block) {
    var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);

    var _code = "canvas = image.new(size = (" + value_wh + "))\n";
    return _code;
}
Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
        this.appendValueInput("rgb_value")
            .setCheck(null)
            .appendField("");
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_fill_screen_with_rgb_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['ai_lcd_fill_screen_with_rgb'] = function (block) {
    var value_name = Blockly.Python.valueToCode(block, 'rgb_value', Blockly.Python.ORDER_ATOMIC);
    // TODO: Assemble Python into code variable.
    if (value_name.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == value_name.length && (d = parseInt(value_name.substring(1, 3), 16),
                e = parseInt(value_name.substring(3, 5), 16),
                f = parseInt(value_name.substring(5, 7), 16))
        } catch (g) { }
        // TODO: Assemble Python into code variable.
        value_name = "(" + d + "," + e + "," + f + ")";
    }
    var code = ``;
    return code;
};
Blockly.Blocks['ai_lcd_textcarvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_on_draw);
        this.appendValueInput("POSA")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_start_coord);
        this.appendValueInput("CONTENT")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_content);
        this.appendValueInput("COLOR")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_color);
        this.appendValueInput("Scale")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_draw_text_font_size);
        this.setInputsInline(true);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_textcarvas_TOOLTIP);
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_lcd_textcarvas = function (block) {
    var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
    var _code = ""
    if (color.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        // color=(" + d + "," + e + "," + f + ")" + ", font_size=" + size + ")\n"
        _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = (' + d + ',' + e + ',' + f + ') , thickness = 1)\n'; // #在红色画布上写下hello world
    } else if (color.charAt(0) != '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var scale = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        _code = 'canvas.draw_string(' + xy + ', ' + content + ', scale = ' + scale + ', color = ' + color + ', thickness = 1)\n' + // #在红色画布上写下hello world
            '';
    }
    return _code;
}
Blockly.Blocks['ai_lcd_linecarvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_draw_line);
        this.appendValueInput("POSA")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_start_coord);
        this.appendValueInput("POSB")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_end_coord);
        this.appendValueInput("COLOR")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_color);
        this.appendValueInput("Scale")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_text_thick);
        this.setInputsInline(true);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_linecarvas_TOOLTIP);
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_lcd_linecarvas = function (block) {
    var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
    if (color.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }

        var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
        var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=(" + d + "," + e + "," + f + "), thickness=" + size + ")\n";
    } else if (color.charAt(0) != '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }

        var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var xy2 = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
        var _code = "canvas.draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n";
    }
    return _code;
}
Blockly.Blocks['ai_lcd_ractanglecarvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_on_draw)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.image_process_text_filled, "fillrect"],
                [Blockly.Msg.image_process_text_stroked, "rect"]
            ]), "rect_type")
            .appendField(Blockly.Msg.image_process_draw_rectangle_text);
        this.appendValueInput("POSA")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_start_coord);
        this.appendValueInput("POSB")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_end_coord);
        this.appendValueInput("COLOR")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_color);
        // this.appendValueInput("Scale")
        //     .setCheck("Number")
        //     .appendField(Blockly.Msg.image_process_text_thick);
        this.setInputsInline(true);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#5bb2d6");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('rect_type');
            var TOOLTIPS = {
                'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
                'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_lcd_ractanglecarvas = function (block) {
    var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);

    var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
    var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
    var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
    var _code = ''
    if (color.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        _code = `canvas.draw_rectangle(${xy},${size}, color=(${d},${e},${f}), thickness=${type})
`
    } else if (color.charAt(0) != '#') {
        _code = `canvas.draw_rectangle(${xy},${size}, color=${color}, thickness=${type})
`
    }
    return _code;
}
Blockly.Blocks['lcd_set_position'] = {
    init: function () {
        this.appendValueInput("POSX")
            .setCheck("Number")
            .appendField("X:");
        this.appendValueInput("POSY")
            .setCheck("Number")
            .appendField("Y:");
        this.setOutput(true, "String");
        this.setInputsInline(true);
        this.setColour(screenColor);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python['lcd_set_position'] = function (block) {
    var pos_x = Blockly.Python.valueToCode(block, 'POSX', Blockly.Python.ORDER_ATOMIC);
    var pos_y = Blockly.Python.valueToCode(block, 'POSY', Blockly.Python.ORDER_ATOMIC);
    var code = pos_x + "," + pos_y;
    return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Blocks['lcd_set_color'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.COLOR)
            .appendField(new Blockly.FieldColour("#ff0000"), "COLOR");
        this.setOutput(true, "String");
        this.setColour("#5bb2d6");
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python['lcd_set_color'] = function (block) {
    var code = block.getFieldValue('COLOR');
    return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Blocks['ai_lcd_draw_rectangle'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_on_draw)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.image_process_text_filled, "fillrect"],
                [Blockly.Msg.image_process_text_stroked, "rect"]
            ]), "rect_type")
            .appendField(Blockly.Msg.image_process_draw_rectangle_text);
        this.appendValueInput("POSA")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_start_coord);
        this.appendValueInput("POSB")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_size);
        this.appendValueInput("COLOR")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_color);
        this.setInputsInline(true);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour(screenColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('rect_type');
            var TOOLTIPS = {
                'fillrect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
                'rect': Blockly.Msg.ai_lcd_ractanglecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_lcd_draw_rectangle = function (block) {
    var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
    var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
    var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(block, 'POSB', Blockly.Python.ORDER_ATOMIC);
    // console.log(xy.split(','),size.split(','))
    let a = xy.split(',')
    let b = size.split(',')
    let w = Number(a[0]) + Number(b[0])
    let h = Number(a[1]) + Number(b[1])
    var _code = ''
    if (color.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=(${d},${e},${f}), thickness=${type})
`
    } else if (color.charAt(0) != '#') {
        _code = `canvas.draw_rectangle(${xy}, ${a[0]}+${b[0]},${a[1]}+${b[1]}, color=${color}, thickness=${type})
`
    }
    return _code;
}

Blockly.Blocks['ai_lcd_drawcirclecarvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_on_draw)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.image_process_text_filled, "fillrect"],
                [Blockly.Msg.image_process_text_stroked, "rect"]
            ]), "rect_type")
            .appendField(Blockly.Msg.image_process_draw_circle_text);
        this.appendValueInput("POSA")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_draw_circle_text_start);
        this.appendValueInput("Scale")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_text_radius);
        this.appendValueInput("COLOR")
            .setCheck("String")
            .appendField(Blockly.Msg.image_process_text_color);
        this.appendValueInput("Scale_0")
            .setCheck("Number")
            .appendField(Blockly.Msg.image_process_text_thick);
        this.setInputsInline(true);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour(screenColor);
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('rect_type');
            var TOOLTIPS = {
                'fillrect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_filled),
                'rect': Blockly.Msg.ai_lcd_drawcirclecarvas_TOOLTIP.replace('%1', Blockly.Msg.image_process_text_stroked)
            };
            return TOOLTIPS[mode];
        });
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_lcd_drawcirclecarvas = function (block) {
    var color = Blockly.Python.valueToCode(block, 'COLOR', Blockly.Python.ORDER_ATOMIC);
    if (color.charAt(0) == '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
        var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
        var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + type + ")\n";
    } else if (color.charAt(0) != '#') {
        var d = 0,
            e = 0,
            f = 0;
        try {
            7 == color.length && (d = parseInt(color.substring(1, 3), 16),
                e = parseInt(color.substring(3, 5), 16),
                f = parseInt(color.substring(5, 7), 16))
        } catch (g) { }
        var type = block.getFieldValue('rect_type') == "fillrect" ? "-1" : "1";
        var th = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
        var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
        var th0 = Blockly.Python.valueToCode(block, 'Scale_0', Blockly.Python.ORDER_ATOMIC);
        var _code = "canvas.draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + type + ")\n";
    }
    return _code;
}

Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_text_on_canvas)

            .appendField(Blockly.Msg.image_process_draw_image_title);
        this.appendValueInput("image_path")
            .setCheck(null)
            .appendField(Blockly.Msg.image_process_draw_sensor_image_path);
        this.appendValueInput("scale_y")
            .setCheck(null)
            .appendField(Blockly.Msg.OLCD_COORDINATE);
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_draw_image_on_canvas_TOOLTIP);
        this.setHelpUrl("");
    }
};


Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) {
    var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
    var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC);
    var code = '' +
        'canvas.draw_image(' + value_image_path + ',' + value_scale_y + ',alpha=1)\n' +
        '\n';

    return code;
};
Blockly.Blocks['ai_lcd_rotation'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.LCD_CANVAS)

            .appendField(Blockly.Msg.image_process_set_lcd_rotation)
            .appendField(new Blockly.FieldDropdown([
                ["0°", "0"],
                ["90°", "90"],
                ["180°", "180"],
                ["270°", "270"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.CATEGORY_SHOW)
        this.setInputsInline(true);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_rotation_TOOLTIP);
        this.setHelpUrl('');
    }
}

Blockly.Python.ai_lcd_rotation = function (block) {
    var dropdown_name = block.getFieldValue('DEGREE');

    let w = ''
    let h = ''
    if (dropdown_name == 90 || dropdown_name == 270) {
        w = 240
        h = 320
    } else {
        w = 320
        h = 240
    }
    var _code = `
`;
    return _code;;
}
Blockly.Blocks['ai_lcd_showcarvas_set_display'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_show_canvas)
            ;
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_showcarvas_set_display_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python.ai_lcd_showcarvas_set_display = function (block) {
    Blockly.Python.definitions_['import_base64'] = `import base64`
    Blockly.Python.definitions_['import_time'] = `import time`
    var code = `
`;
    return code;
};
Blockly.Blocks['ai_lcd_clearcanvas'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.image_process_clear_canvas_2);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(screenColor);
        this.setTooltip(Blockly.Msg.ai_lcd_clearcanvas_TOOLTIP);
        this.setHelpUrl('');
    }
}

Blockly.Python.ai_lcd_clearcanvas = function (block) {
    var _code = "canvas.clear()\n";
    return _code;;
}
export default Blockly