"use strict";

/*
     _    ___   ____            _      
    / \  |_ _| | __ )  __ _ ___(_) ___ 
   / _ \  | |  |  _ \ / _` / __| |/ __|
  / ___ \ | |  | |_) | (_| \__ \ | (__ 
 /_/   \_\___| |____/ \__,_|___/_|\___|
*/
Blockly.Blocks['ai_k210_button_read_pressed'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_basic_button_when).appendField(new Blockly.FieldDropdown([["A", "a"], ["B", "b"], ["C", "c"]]), "button_type").appendField(Blockly.Msg.ai_basic_pressed);
    this.setOutput(true, null);
    this.setColour("#d42b03");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_k210_button_read_pressed'] = function (block) {
  Blockly.Python.definitions_['import_define_x_ai_button'] = '' + 'from fpioa_manager import *\n' + 'from Maix import FPIOA, GPIO\n' + '\n' + '_gp_side_buttons = [9, 10, 11]\n' + '\n' + 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' + 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' + 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' + '\n' + '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' + '\n';

  var _type = block.getFieldValue('button_type');

  var code = '_gp_side_' + _type + '.value() == 1';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['ai_k210_button_read_released'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_basic_button_when).appendField(new Blockly.FieldDropdown([["A", "a"], ["B", "b"], ["C", "c"]]), "button_type_released").appendField(Blockly.Msg.ai_basic_released);
    this.setOutput(true, null);
    this.setColour("#d42b03");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_k210_button_read_released'] = function (block) {
  Blockly.Python.definitions_['import_define_x_ai_button'] = '' + 'from fpioa_manager import *\n' + 'from Maix import FPIOA, GPIO\n' + '\n' + '_gp_side_buttons = [9, 10, 11]\n' + '\n' + 'FPIOA().set_function(_gp_side_buttons[0],FPIOA.GPIO0)\n' + 'FPIOA().set_function(_gp_side_buttons[1],FPIOA.GPIO1)\n' + 'FPIOA().set_function(_gp_side_buttons[2],FPIOA.GPIO2)\n' + '\n' + '_gp_side_a = GPIO(GPIO.GPIO0,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_b = GPIO(GPIO.GPIO1,GPIO.IN,GPIO.PULL_UP)\n' + '_gp_side_c = GPIO(GPIO.GPIO2,GPIO.IN,GPIO.PULL_UP)\n' + '\n';

  var _type = block.getFieldValue('button_type_released');

  var code = '_gp_side_' + _type + '.value() == 0';
  return [code, Blockly.Python.ORDER_CONDITIONAL];
};

Blockly.Blocks['ai_k210_led_light_up'] = {
  init: function init() {
    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");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_k210_led_light_up'] = function (block) {
  var dropdown_type = block.getFieldValue('type');
  Blockly.Python.definitions_['k210_led_light_def'] = '' + 'from fpioa_manager import *\n' + 'from Maix import GPIO\n' + '\n' + 'fm.register(31, fm.fpioa.GPIO3)\n' + 'fm.register(32, fm.fpioa.GPIO4)\n' + '\n' + '_led_red=GPIO(GPIO.GPIO3,GPIO.OUT)\n' + '_led_blue=GPIO(GPIO.GPIO4,GPIO.OUT)\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = '_led_' + dropdown_type + '.value(1)\n';
  return code;
};

Blockly.Blocks['ai_k210_led_light_off'] = {
  init: function init() {
    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");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_k210_led_light_off'] = function (block) {
  var dropdown_type = block.getFieldValue('type');
  Blockly.Python.definitions_['k210_led_light_def'] = '' + 'from fpioa_manager import *\n' + 'from Maix import GPIO\n' + '\n' + 'fm.register(31, fm.fpioa.GPIO3)\n' + 'fm.register(32, fm.fpioa.GPIO4)\n' + '\n' + '_led_red=GPIO(GPIO.GPIO3,GPIO.OUT)\n' + '_led_blue=GPIO(GPIO.GPIO4,GPIO.OUT)\n' + '\n'; // TODO: Assemble Python into code variable.

  var code = '_led_' + dropdown_type + '.value(0)\n';
  return code;
};
/*
     _    ___   ___                              ____                              
    / \  |_ _| |_ _|_ __ ___   __ _  __ _  ___  |  _ \ _ __ ___   ___ ___  ___ ___ 
   / _ \  | |   | || '_ ` _ \ / _` |/ _` |/ _ \ | |_) | '__/ _ \ / __/ _ \/ __/ __|
  / ___ \ | |   | || | | | | | (_| | (_| |  __/ |  __/| | | (_) | (_|  __/\__ \__ \
 /_/   \_\___| |___|_| |_| |_|\__,_|\__, |\___| |_|   |_|  \___/ \___\___||___/___/
                                    |___/                                          
*/


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

Blockly.Python.ai_lcd_screeninit = function (block) {
  var checkbox_name = block.getFieldValue('DEGREE'); //var dropdown_name = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False";

  Blockly.Python.definitions_.import_lcd = "import lcd";
  Blockly.Python.definitions_.import_image = "import image";
  var _code = "lcd.init(type=1,freq=15000000,width=240,height=240,color=(0,0,0))\n";
  _code += "lcd.rotation(1)\n";
  _code += "lcd.clear(lcd.BLACK)\n";
  return _code;
  ;
};

Blockly.Blocks['ai_lcd_rotation'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_set_lcd_rotation).appendField(new Blockly.FieldDropdown([["0°", "1"], ["90°", "2"], ["180°", "3"], ["270°", "0"]]), "DEGREE");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

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

  var _code = "lcd.rotation(" + dropdown_name + ")\n";

  return _code;
  ;
};

Blockly.Blocks['ai_lcd_filp'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_set_lcd_mirror_flip).appendField(new Blockly.FieldCheckbox('TRUE'), 'TextCheckBox');
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_filp = function (block) {
  var _tf = block.getFieldValue('TextCheckBox') == 'TRUE' ? "True" : "False";

  var _code = "lcd.mirror(" + _tf + ")\n";

  return _code;
};

Blockly.Blocks['ai_lcd_screen'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_set_filled_screen_color).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_set_filled_screen_color_red, "RED"], [Blockly.Msg.image_process_set_filled_screen_color_green, "GREEN"], [Blockly.Msg.image_process_set_filled_screen_color_blue, "BLUE"], [Blockly.Msg.image_process_set_filled_screen_color_purple, "PURPLE"], [Blockly.Msg.image_process_set_filled_screen_color_cyan, "CYAN"], [Blockly.Msg.image_process_set_filled_screen_color_orange, "ORANGE"], [Blockly.Msg.image_process_set_filled_screen_color_yellow, "YELLOW"], [Blockly.Msg.image_process_set_filled_screen_color_black, "BLACK"], [Blockly.Msg.image_process_set_filled_screen_color_white, "WHITE"]]), "COLOR");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_screen = function (block) {
  var colour_name = block.getFieldValue('COLOR');

  var _code = "lcd.clear(lcd." + colour_name + ")\n";

  return _code;
};

Blockly.Blocks['ai_lcd_fill_screen_with_rgb'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_set_filled_screen_color);
    this.appendValueInput("rgb_value").setCheck(null).appendField("");
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip("");
    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.

  var code = 'lcd.clear(' + value_name + ')\n';
  return code;
};

Blockly.Blocks['ai_lcd_clear'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_clear_lcd);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_clear = function (block) {
  var _code = "lcd.clear(lcd.BLACK)\n";
  return _code;
};

Blockly.Blocks['ai_lcd_rgb_value_input'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_rgb_r);
    this.appendValueInput("rgb_value_r").setCheck(null).appendField("");
    this.appendDummyInput().appendField(Blockly.Msg.image_process_rgb_g);
    this.appendValueInput("rgb_value_g").setCheck(null).appendField("");
    this.appendDummyInput().appendField(Blockly.Msg.image_process_rgb_b);
    this.appendValueInput("rgb_value_b").setCheck(null).appendField("");
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip("");
    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];
};

Blockly.Blocks.ai_lcd_XY = {
  init: function init() {
    var _input = this.appendDummyInput();

    this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
    this.setColour("#5bb2d6");
    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.ai_lcd_WH = {
  init: function init() {
    var _input = this.appendDummyInput();

    this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
    this.setColour("#5bb2d6");
    this.setOutput(!0, "Boolean");

    _input.appendField(Blockly.Msg.image_process_wh_width);

    this.appendValueInput("A").setCheck("Number");
    _input = this.appendDummyInput();

    _input.appendField(Blockly.Msg.image_process_wh_height);

    this.appendValueInput("B").setCheck("Number");
    this.setInputsInline(!0);
  }
};

Blockly.Python.ai_lcd_WH = 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['ai_lcd_colortext'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_show_text);
    this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_show_text_color).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"], [Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"], [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"], [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"], [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"], [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"], [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"], [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"], [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]]), "COLOR");
    this.appendDummyInput().appendField(Blockly.Msg.image_process_lcd_show_text_bg_color).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_lcd_show_text_color_black, "BLACK"], [Blockly.Msg.image_process_lcd_show_text_color_white, "WHITE"], [Blockly.Msg.image_process_lcd_show_text_color_red, "RED"], [Blockly.Msg.image_process_lcd_show_text_color_green, "GREEN"], [Blockly.Msg.image_process_lcd_show_text_color_blue, "BLUE"], [Blockly.Msg.image_process_lcd_show_text_color_purple, "PURPLE"], [Blockly.Msg.image_process_lcd_show_text_color_cyan, "CYAN"], [Blockly.Msg.image_process_lcd_show_text_color_orange, "ORANGE"], [Blockly.Msg.image_process_lcd_show_text_color_yellow, "YELLOW"]]), "BCOLOR");
    this.appendValueInput("CONTENT").setCheck("String").appendField(Blockly.Msg.image_process_text_content);
    /* this.appendDummyInput()
        .appendField(Blockly.Msg.LCDDT); */

    this.appendValueInput("POSA").setCheck("String").appendField(Blockly.Msg.image_process_text_start_coord);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python['ai_lcd_colortext'] = function (block) {
  var color = block.getFieldValue("COLOR");
  var bcolor = block.getFieldValue("BCOLOR");
  var content = Blockly.Python.valueToCode(block, 'CONTENT', 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 = "lcd.draw_string(" + xy + ", " + content + ", lcd." + color + ", lcd." + bcolor + ")\n"; //, scale=" + size + "
  // return [_code, Blockly.Python.ORDER_ATOMIC]


  return _code;
};

Blockly.Blocks["ai_lcd_createnonecarvas"] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_create_blank_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.image_process_text_size); // this.appendDummyInput()
    //     .appendField(Blockly.Msg.LCDDCC_F)
    //     .appendField(new Blockly.FieldCheckbox("TRUE"), "check")
    //     .appendField(Blockly.Msg.LCDDCC_I)
    //     .appendField(new Blockly.FieldTextInput(""), "text");

    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_createnonecarvas = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);

  var _code = variable_name + " = image.Image(size=(" + value_wh + "))\n";

  return _code;
};

Blockly.Blocks["ai_lcd_fillcanvas"] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.appendValueInput("color").setCheck(null).appendField(Blockly.Msg.image_process_text_let_canvas_filled_with_color);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_fillcanvas = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);

  var _code = variable_name + '.draw_rectangle(0,0, ' + variable_name + '.width(),' + variable_name + '.height(), color=' + value_color + ', thickness=1, fill=True)\n';

  return _code;
};

Blockly.Blocks["ai_lcd_createcarvas"] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_create_image_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.appendDummyInput().appendField(Blockly.Msg.image_process_create_image_canvas_path).appendField(new Blockly.FieldTextInput("/sd/preset/images/splash_bg.jpg"), "text");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_createcarvas = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var checkbox_name = block.getFieldValue('check') == 'TRUE' ? "True" : "False";
  var text_name = block.getFieldValue('text');

  var _code = variable_name + " = image.Image(\"" + text_name + "\")\n";

  return _code;
};

Blockly.Blocks['ai_lcd_showcarvas_set_cord'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_set_canvas_setup).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_text_start_coord_as);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_lcd_showcarvas_set_cord = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = "_" + variable_name + "_x, _" + variable_name + "_y = " + value_name + "\n";
  return code;
};

Blockly.Blocks['ai_lcd_showcarvas_set_display'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_show_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_lcd_showcarvas_set_display = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = "lcd.display(" + variable_name + ", oft=(_" + variable_name + "_x,_" + variable_name + "_y))\n";
  return code;
};

Blockly.Blocks['ai_lcd_showcarvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_show_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem");
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_text_start_coord);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5cb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_lcd_showcarvas = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_name = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = "lcd.display(" + variable_name + ", oft=(" + value_name + "))\n";
  return code;
};

Blockly.Blocks['ai_lcd_clearcanvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_clear_canvas_1).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_clear_canvas_2);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_clearcanvas = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

  var _code = variable_name + ".clear()\n";

  return _code;
  ;
};

Blockly.Blocks['ai_lcd_textcarvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_text.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_text);
    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.appendDummyInput().appendField(Blockly.Msg.image_process_draw_text_if_monospace).appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_textcarvas = 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 bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False"; // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";

    var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
    var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

    var _code = variable_name + ".draw_string(" + xy + ", " + content + ", color=(" + d + "," + e + "," + f + "), scale=" + size + ", mono_space=" + bool + ")\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 bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False"; // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";

    var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
    var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
    var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

    var _code = variable_name + ".draw_string(" + xy + ", " + content + ", color=" + color + ", scale=" + size + ", mono_space=" + bool + ")\n";
  }

  return _code;
};

Blockly.Blocks['ai_lcd_characterscarvas'] = {
  init: function () {
      this.appendDummyInput()
          .appendField(new Blockly.FieldImage("blockly/media/lcd_draw_hanzi_header.png", 45, 45, { alt: "*", flipRtl: "FALSE" }));
      this.appendDummyInput()
          .appendField(Blockly.Msg.image_process_text_on_canvas)
          .appendField(new Blockly.FieldVariable("canvas"), "varitem")
          .appendField(Blockly.Msg.image_process_text_on_draw + Blockly.Msg.image_process_draw_characters);
      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.appendDummyInput()
          .appendField(Blockly.Msg.image_process_draw_text_if_monospace)
          .appendField(new Blockly.FieldCheckbox("FALSE"), "bool");
      this.setInputsInline(false);
      this.setPreviousStatement(true);
      this.setNextStatement(true);
      this.setColour("#5bb2d6");
      this.setTooltip('');
      this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_characterscarvas = 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 bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
      // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
      var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
      var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
      var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
      var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
      var _code = variable_name + ".draw_string(" + xy + ", " + content + ", color=(" + d + "," + e + "," + f + "), scale=" + size + ", mono_space=" + bool + ")\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 bool = block.getFieldValue('bool') == "TRUE" ? "True" : "False";
      // var bool = Blockly.Python.valueToCode(block, 'POSC', Blockly.Python.ORDER_ATOMIC) == "TRUE" ? "True" : "False";
      var content = Blockly.Python.valueToCode(block, 'CONTENT', Blockly.Python.ORDER_ATOMIC);
      var xy = Blockly.Python.valueToCode(block, 'POSA', Blockly.Python.ORDER_ATOMIC);
      var size = Blockly.Python.valueToCode(block, 'Scale', Blockly.Python.ORDER_ATOMIC);
      var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
      var _code = variable_name + ".draw_string(" + xy + ", " + content + ", color=" + color + ", scale=" + size + ", mono_space=" + bool + ")\n";
  }
  return _code;
}

Blockly.Blocks['ai_lcd_linecarvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_line.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_text_on_draw + 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(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    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 variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

    var _code = variable_name + ".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 variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

    var _code = variable_name + ".draw_line(" + xy + ", " + xy2 + ", color=" + color + ", thickness=" + size + ")\n";
  }

  return _code;
};

Blockly.Blocks['ai_lcd_ractanglecarvas'] = {
  init: function init() {
    // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_rectangle.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").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.appendValueInput("Scale").setCheck("Number").appendField(Blockly.Msg.image_process_text_thick);
    this.setInputsInline(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_lcd_ractanglecarvas = 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 variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var type = block.getFieldValue('rect_type') == "fillrect" ? "True" : "False";
    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 = variable_name + ".draw_rectangle(" + xy + ", " + size + ", color=(" + d + "," + e + "," + f + "), thickness=" + th + ", fill=" + type + ")\n";
  } else if (color.charAt(0) != '#') {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var type = block.getFieldValue('rect_type') == "fillrect" ? "True" : "False";
    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 = variable_name + ".draw_rectangle(" + xy + ", " + size + ", color=" + color + ", thickness=" + th + ", fill=" + type + ")\n";
  }

  return _code;
};

Blockly.Blocks['ai_lcd_drawcirclecarvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_circle.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    })); // this.appendDummyInput()
    //     .appendField(
    //         new Blockly.FieldImage("./../blockly/media/line.png", 25, 25, "15"));

    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").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(false);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5bb2d6");
    this.setTooltip('');
    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 variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var type = block.getFieldValue('rect_type') == "fillrect" ? "True" : "False";
    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 = variable_name + ".draw_circle(" + xy + ", " + th + ", color=(" + d + ", " + e + ", " + f + "), thickness=" + th0 + ", fill=" + 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 variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var type = block.getFieldValue('rect_type') == "fillrect" ? "True" : "False";
    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 = variable_name + ".draw_circle(" + xy + ", " + th + ", color=" + color + ", thickness=" + th0 + ", fill=" + type + ")\n";
  }

  return _code;
};

Blockly.Blocks['ai_lcd_draw_cross_sign'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_cross.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_draw_cross_title);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_draw_cross_centerpos);
    this.appendValueInput("size").setCheck(null).appendField(Blockly.Msg.image_process_draw_cross_length);
    this.appendValueInput("thickness").setCheck(null).appendField(Blockly.Msg.image_process_draw_cross_thick);
    this.appendValueInput("color").setCheck(null).appendField(Blockly.Msg.image_process_draw_cross_color);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_draw_cross_sign'] = function (block) {
  var color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);

  if (color.charAt(0) == '#') {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
    var value_size = Blockly.Python.valueToCode(block, 'size', Blockly.Python.ORDER_ATOMIC);
    var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
    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) {} // TODO: Assemble Python into code variable.


    var code = variable_name + '.draw_cross(' + value_xy + ', color=(' + d + ', ' + e + ', ' + f + '), size=' + value_size + ', thickness=' + value_thickness + ')\n';
  } else if (color.charAt(0) != '#') {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
    var value_size = Blockly.Python.valueToCode(block, 'size', Blockly.Python.ORDER_ATOMIC);
    var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

    var code = variable_name + '.draw_cross(' + value_xy + ', color=' + color + ', size=' + value_size + ', thickness=' + value_thickness + ')\n';
  }

  return code;
};

Blockly.Blocks['ai_lcd_draw_arrow_sign'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_arrow.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_draw_arrow_title);
    this.appendValueInput("xy1").setCheck(null).appendField(Blockly.Msg.image_process_draw_arrow_start);
    this.appendValueInput("xy2").setCheck(null).appendField(Blockly.Msg.image_process_draw_arrow_end);
    this.appendValueInput("color").setCheck(null).appendField(Blockly.Msg.image_process_draw_arrow_color);
    this.appendValueInput("thickness").setCheck(null).appendField(Blockly.Msg.image_process_draw_arrow_thick);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_draw_arrow_sign'] = function (block) {
  // TODO: Assemble Python into code variable.
  var color = Blockly.Python.valueToCode(block, 'color', Blockly.Python.ORDER_ATOMIC);

  if (color.charAt(0) == '#') {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var value_xy1 = Blockly.Python.valueToCode(block, 'xy1', Blockly.Python.ORDER_ATOMIC);
    var value_xy2 = Blockly.Python.valueToCode(block, 'xy2', Blockly.Python.ORDER_ATOMIC);
    var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC);
    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) {} // TODO: Assemble Python into code variable.


    var code = variable_name + '.draw_arrow(' + value_xy1 + ',' + value_xy2 + ', color=(' + d + ', ' + e + ', ' + f + '), thickness=' + value_thickness + ')\n';
  } else if (color.charAt(0) != '#') {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var value_xy1 = Blockly.Python.valueToCode(block, 'xy1', Blockly.Python.ORDER_ATOMIC);
    var value_xy2 = Blockly.Python.valueToCode(block, 'xy2', Blockly.Python.ORDER_ATOMIC);
    var value_thickness = Blockly.Python.valueToCode(block, 'thickness', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

    var code = variable_name + '.draw_arrow(' + value_xy1 + ',' + value_xy2 + ', color=(' + color + '), thickness=' + value_thickness + ')\n';
  }

  return code;
};

Blockly.Blocks['ai_lcd_draw_image_on_canvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/lcd_draw_image.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_on_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_draw_image_title);
    this.appendValueInput("image_path").setCheck(null).appendField(Blockly.Msg.image_process_draw_image_title_image_path);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_text_start_coord);
    this.appendValueInput("scale_x").setCheck(null).appendField(Blockly.Msg.image_process_draw_image_scale_x);
    this.appendValueInput("scale_y").setCheck(null).appendField(Blockly.Msg.image_process_draw_image_scale_y);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5bb2d6");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_draw_image_on_canvas'] = function (block) {
  // TODO: Assemble Python into code variable.
  // nav_up = image.Image("/sd/preset/images/arrow_up_filled.jpg")
  // splash.draw_image(nav_up, 5, 5)
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_image_path = Blockly.Python.valueToCode(block, 'image_path', Blockly.Python.ORDER_ATOMIC);
  var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var value_scale_x = Blockly.Python.valueToCode(block, 'scale_x', Blockly.Python.ORDER_ATOMIC);
  var value_scale_y = Blockly.Python.valueToCode(block, 'scale_y', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = '' + variable_name + '.draw_image(image.Image(' + value_image_path + '), ' + value_xy + ',  x_scale=' + value_scale_x + ',  y_scale=' + value_scale_y + ' )';
  '\n';
  return code;
};

Blockly.Blocks['ai_img_save'] = {
  init: function init() {
    this.appendValueInput("save_path").setCheck(null).appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_img_save);
    this.appendDummyInput().appendField(Blockly.Msg.image_process_img_save_quality).appendField(new Blockly.FieldNumber(90, 0, 100), "compression").appendField("%");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_img_save'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var save_path_location = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  var compression_rate = block.getFieldValue('compression'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.save(' + save_path_location + ', quality=' + compression_rate + ')\n';
  return code;
};

Blockly.Blocks['ai_lcd_invert_color'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_color_invert);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_invert_color'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = variable_name + '.invert()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_lcd_resizecanvas'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_resize_to);
    this.appendValueInput("wh").setCheck(null);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_resizecanvas'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.resize(' + wh + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_lcd_color_scheme'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_color_scheme_convert).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_color_scheme_bw, "to_grayscale(1)"], [Blockly.Msg.image_process_color_scheme_rgb, "to_rgb565(1)"]]), "color_scheme");
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_color_scheme'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_vari = block.getFieldValue('color_scheme'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + dropdown_vari; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_lcd_ai_pix'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_pixtovec_text_first).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_pixtovec_v2p, ".ai_to_pix()"], [Blockly.Msg.image_process_pixtovec_p2v, ".pix_to_ai()"]]), "ai_pix_type").appendField(Blockly.Msg.image_process_pixtovec_conversion);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_ai_pix'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_vari = block.getFieldValue('ai_pix_type'); // TODO: Assemble Python into code variable.

  var code = 'a = ' + variable_name + dropdown_vari + '\n'; // TODO: Change ORDER_NONE to the correct strength.

  return code;
};

Blockly.Blocks['ai_lcd_img_cut'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_text_let_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_imgcut_cutting);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_imgcut_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.image_process_imgcut_size);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_lcd_img_cut'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.
  // TODO: Change ORDER_NONE to the correct strength.

  var code = variable_name + '.cut(' + xy + ',' + wh + ')';
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_statistics'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_get_statistics_to_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.image_process_get_statistics_get_analysis);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.image_process_get_statistics_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.image_process_get_statistics_size);
    this.appendValueInput("bins").setCheck(null).appendField(Blockly.Msg.image_process_get_statistics_boxes);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_get_statistics'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  var bins = Blockly.Python.valueToCode(block, 'bins', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.get_statistics(bins=' + bins + ',roi=(' + xy + ',' + wh + '))'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_histogram'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_histogram_get).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_get_histogram_compute);
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_histogram_region);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_get_histogram_region_xy);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_get_histogram_region_wh);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_get_histogram'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.get_histogram(roi=(' + value_xy + ',' + value_wh + '))'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_histogram_percentile'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_histogram_details_1).appendField(new Blockly.FieldVariable("hist"), "varitem").appendField(Blockly.Msg.ai_vision_get_histogram_details_get);
    this.appendValueInput("perc").setCheck(null);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  }
};

Blockly.Python['ai_vision_get_histogram_percentile'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_perc = Blockly.Python.valueToCode(block, 'perc', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.get_percentile(' + value_perc + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_histogram_percentile_detail'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_histogram_percentile_1).appendField(new Blockly.FieldVariable("percentile"), "varitem");
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_histogram_percentile_2).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_get_histogram_percentile_3, "value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_4, "l_value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_5, "a_value()"], [Blockly.Msg.ai_vision_get_histogram_percentile_6, "b_value()"]]), "option");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.openmv.io/library/omv.image.html#id3");
  }
};

Blockly.Python['ai_vision_get_histogram_percentile_detail'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_option = block.getFieldValue('option');
  var code = variable_name + '.' + dropdown_option; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_lab_rgb_conversion'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_lab_rgb_conversion_exec).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_lab_rgb_conversion_torgb, "lab_to_rgb"], [Blockly.Msg.image_process_lab_rgb_conversion_tolab, "rgb_to_lab"]]), "rgblab");
    this.appendValueInput("color_tuple").setCheck(null).appendField(Blockly.Msg.image_process_lab_rgb_conversion_tuple);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_lab_rgb_conversion'] = function (block) {
  var type = block.getFieldValue('rgblab');
  var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = 'image.' + type + '(' + tuple + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_rgb_grayscale_conversion'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_exec).appendField(new Blockly.FieldDropdown([[Blockly.Msg.image_process_rgb_grayscale_conversion_torgb, "grayscale_to_rgb"], [Blockly.Msg.image_process_rgb_grayscale_conversion_togray, "rgb_to_grayscale"]]), "rgb_g");
    this.appendValueInput("color_tuple").setCheck(null).appendField(Blockly.Msg.image_process_rgb_grayscale_conversion_set);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_rgb_grayscale_conversion'] = function (block) {
  var type = block.getFieldValue('rgb_g');
  var tuple = Blockly.Python.valueToCode(block, 'color_tuple', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.addVariable('rgb_tuple', "", true); // TODO: Assemble Python into code variable.

  var code = 'image.' + type + '(' + tuple + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
     _    ___    ____                               
    / \  |_ _|  / ___|__ _ _ __ ___   ___ _ __ __ _ 
   / _ \  | |  | |   / _` | '_ ` _ \ / _ \ '__/ _` |
  / ___ \ | |  | |__| (_| | | | | | |  __/ | | (_| |
 /_/   \_\___|  \____\__,_|_| |_| |_|\___|_|  \__,_|

*/


Blockly.Blocks.ai_camera_wh = {
  init: function init() {
    var _input = this.appendDummyInput();

    this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
    this.setColour("#60c1bb");
    this.setOutput(!0, "Boolean");

    _input.appendField(Blockly.Msg.W);

    this.appendValueInput("A").setCheck("Number");
    _input = this.appendDummyInput();

    _input.appendField(Blockly.Msg.H);

    this.appendValueInput("B").setCheck("Number");
    this.setInputsInline(!0);
  }
};

Blockly.Python.ai_camera_wh = 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['ai_camera_init'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/camera_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_camera_init);
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_camera_set_size).appendField(new Blockly.FieldDropdown([["QVGA (320*240)", "QVGA"], ["QQVGA (160*120)", "QQVGA"]]), "DEGREE");
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_camera_color_mode).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_camera_color_mode_rgb, "RGB565"], [Blockly.Msg.ai_camera_camera_color_mode_bw, "GRAYSCALE"]]), "DEGREE1");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_init = function (block) {
  var degee = block.getFieldValue('DEGREE');
  var degee1 = block.getFieldValue('DEGREE1');
  var checkbox = block.getFieldValue('checkbox') == 'TRUE';
  var w = block.getFieldValue('w');
  var h = block.getFieldValue('h');
  var degee2 = block.getFieldValue('DEGREE2') || 1;
  var degee3 = block.getFieldValue('DEGREE3') || 1;
  var degee4 = block.getFieldValue('DEGREE4') || 1;
  var degee5 = block.getFieldValue('DEGREE5') || 1;
  var input1 = block.getFieldValue('input1') || 1;
  var input2 = block.getFieldValue('input2') || 1;
  var input3 = block.getFieldValue('input3') || 1;
  Blockly.Python.definitions_.import_sensor = "import sensor";
  var _code = "sensor.reset()\n";
  _code += "sensor.set_pixformat(sensor." + degee1 + ")\n";
  _code += "sensor.set_framesize(sensor." + degee + ")\n";
  _code += "sensor.set_vflip(0)\n";
  _code += "sensor.set_hmirror(0)\n";
  _code += "sensor.skip_frames(30)\n";
  _code += "sensor.run(1)\n";
  return _code;
};

Blockly.Blocks['ai_camera_windows'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_windowing_resize);
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_windowing_w).appendField(new Blockly.FieldNumber(224), "window_w").appendField(Blockly.Msg.ai_camera_windowing_h).appendField(new Blockly.FieldNumber(224), "window_h").appendField(Blockly.Msg.ai_camera_windowing_unit);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_camera_windows'] = function (block) {
  var w = block.getFieldValue('window_w');
  var h = block.getFieldValue('window_h');
  var code = 'sensor.set_windowing((' + w + ',' + h + '))\n';
  return code;
};

Blockly.Blocks['ai_camera_snapshot'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_snapshot);
    this.setOutput(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_snapshot = function (block) {
  Blockly.Python.definitions_.import_sensor = "import sensor";
  var degee = block.getFieldValue('DEGREE');
  var _code = "sensor.snapshot()";
  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_camera_lens_corr'] = {
  init: function init() {
    this.appendValueInput("lens_corr").setCheck(null).appendField(Blockly.Msg.ai_camera_set_lens_corr);
    this.setInputsInline(true);
    this.setOutput(true, null);
    this.setColour("#60c1bb");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_camera_lens_corr'] = function (block) {
  var value_lens_corr = Blockly.Python.valueToCode(block, 'lens_corr', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = value_lens_corr + '.lens_corr(strength = 1.8, zoom = 1.0)'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_camera_image_property_change'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_bcs_set_text_2).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_bcs_vflip, "set_vflip"], [Blockly.Msg.ai_camera_bcs_hmirror, "set_hmirror"], [Blockly.Msg.ai_camera_bcs_wb, "set_auto_whitebal"], [Blockly.Msg.ai_camera_bcs_g, "set_auto_gain"], [Blockly.Msg.ai_camera_bcs_e, "set_auto_exposure"]]), "image_property").appendField(Blockly.Msg.ai_camera_bcs_as_2).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable + Blockly.Msg.ai_camera_bcs_status, "True"], [Blockly.Msg.ai_camera_disable + Blockly.Msg.ai_camera_bcs_status, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_image_property_change = function (block) {
  var degee = block.getFieldValue('DEGREE');
  var dropdown_image_property = block.getFieldValue('image_property');

  var _code = "sensor." + dropdown_image_property + "(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_vflip'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_vflip).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_vflip = function (block) {
  var degee = block.getFieldValue('DEGREE');

  var _code = "sensor.set_vflip(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_hmirror'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_hmirror).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_hmirror = function (block) {
  var degee = block.getFieldValue('DEGREE');

  var _code = "sensor.set_hmirror(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_auto_whitebal'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_auto_whitebal).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_auto_whitebal = function (block) {
  var degee = block.getFieldValue('DEGREE');

  var _code = "sensor.set_auto_whitebal(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_auto_gain'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_auto_gain).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_auto_gain = function (block) {
  var degee = block.getFieldValue('DEGREE');

  var _code = "sensor.set_auto_gain(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_auto_exposure'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_auto_exposure).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_enable, "True"], [Blockly.Msg.ai_camera_disable, "False"]]), "DEGREE");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_auto_exposure = function (block) {
  var degee = block.getFieldValue('DEGREE');

  var _code = "sensor.set_auto_exposure(" + degee + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_bcs_operation'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_bcs_set_text).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_camera_bcs_contrast, "contrast"], [Blockly.Msg.ai_camera_bcs_brightness, "brightness"], [Blockly.Msg.ai_camera_bcs_saturation, "saturation"]]), "image_property").appendField(Blockly.Msg.ai_camera_bcs_as);
    this.appendValueInput("A").setCheck("Number");
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_range);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setInputsInline(!0);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_bcs_operation = function (block) {
  var dropdown_image_property = block.getFieldValue('image_property');

  var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);

  var _code = "sensor.set_" + dropdown_image_property + "(" + _x + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_contrast'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_contrast_to_value);
    this.appendValueInput("A").setCheck("Number");
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_range);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setInputsInline(!0);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_contrast = function (block) {
  var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);

  var _code = "sensor.set_contrast(" + _x + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_brightness'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_brightness_to_value);
    this.appendValueInput("A").setCheck("Number");
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_range);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setInputsInline(!0);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_brightness = function (block) {
  var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);

  var _code = "sensor.set_brightness(" + _x + ")\n";

  return _code;
};

Blockly.Blocks['ai_camera_saturation'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_saturation_value);
    this.appendValueInput("A").setCheck("Number");
    this.appendDummyInput().appendField(Blockly.Msg.ai_camera_set_range);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setInputsInline(!0);
    this.setColour("#60c1bb");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_camera_saturation = function (block) {
  var _x = Blockly.Python.valueToCode(block, "A", Blockly.Python.ORDER_ATOMIC);

  var _code = "sensor.set_saturation(" + _x + ")\n";

  return _code;
};
/*
     _    ___  __     ___     _             
    / \  |_ _| \ \   / (_)___(_) ___  _ __  
   / _ \  | |   \ \ / /| / __| |/ _ \| '_ \ 
  / ___ \ | |    \ V / | \__ \ | (_) | | | |
 /_/   \_\___|    \_/  |_|___/_|\___/|_| |_|
                                            
*/


Blockly.Blocks.ai_lcd_XY_vision = {
  init: function init() {
    var _input = this.appendDummyInput();

    this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
    this.setColour("#f0983e");
    this.setOutput(!0, "Boolean");

    _input.appendField(Blockly.Msg.X);

    this.appendValueInput("A").setCheck("Number");
    _input = this.appendDummyInput();

    _input.appendField(Blockly.Msg.Y);

    this.appendValueInput("B").setCheck("Number");
    this.setInputsInline(!0);
  }
};

Blockly.Python.ai_lcd_XY_vision = 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.ai_lcd_WH_vision = {
  init: function init() {
    var _input = this.appendDummyInput();

    this.setHelpUrl(Blockly.Msg.LOGIC_OPERATION_HELPURL);
    this.setColour("#f0983e");
    this.setOutput(!0, "Boolean");

    _input.appendField(Blockly.Msg.W);

    this.appendValueInput("A").setCheck("Number");
    _input = this.appendDummyInput();

    _input.appendField(Blockly.Msg.H);

    this.appendValueInput("B").setCheck("Number");
    this.setInputsInline(!0);
  }
};

Blockly.Python.ai_lcd_WH_vision = 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['ai_vision_color_analyze'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_analyze_color.png", 50, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_color_analyze_get_result);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_color_analyze_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_color_analyze_size);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_color_analyze'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.addFunction("function", '' + 'def _get_regional_color_analyze_rgb(x, y, w, h):\n' + '    _crd_bounding_box_size = (w, h)\n' + '    _crd_r = [x, y, _crd_bounding_box_size[0], _crd_bounding_box_size[1]] # 50x50 center of QQVGA.\n' + '    _crd_hist = ' + variable_name + '.get_statistics(bins=8,roi=_crd_r)\n' + '    return image.lab_to_rgb((_crd_hist.l_mean(),_crd_hist.a_mean(),_crd_hist.b_mean()))\n' + ''); // TODO: Assemble Python into code variable.

  var code = '_get_regional_color_analyze_rgb(' + xy + ', ' + wh + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_blobs'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_color.png", 50, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_find_blobs_color_region);
    this.appendValueInput("color_threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_color_threshold);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_size);
    this.appendValueInput("area_threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_region_threshold).appendField(new Blockly.FieldCheckbox("FALSE"), "check_area");
    this.appendValueInput("pixels_threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_pixel_threshold).appendField(new Blockly.FieldCheckbox("FALSE"), "check_pixels");
    this.appendValueInput("margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_blobs_margin).appendField(new Blockly.FieldCheckbox("FALSE"), "margin");
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_find_blobs_filtered_region).appendField(new Blockly.FieldCheckbox("FALSE"), "check_merge");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_find_blobs'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var value_color_threshold = Blockly.Python.valueToCode(block, 'color_threshold', Blockly.Python.ORDER_ATOMIC);
  var value_xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var value_wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  var value_area_threshold = Blockly.Python.valueToCode(block, 'area_threshold', Blockly.Python.ORDER_ATOMIC);
  var value_pixels_threshold = Blockly.Python.valueToCode(block, 'pixels_threshold', Blockly.Python.ORDER_ATOMIC);
  var checkbox_check_area = block.getFieldValue('check_area') == 'TRUE';
  var checkbox_check_pixels = block.getFieldValue('check_pixels') == 'TRUE';
  var checkbox_check_merge = block.getFieldValue('check_merge') == 'TRUE';
  var value_margin = Blockly.Python.valueToCode(block, 'margin', Blockly.Python.ORDER_ATOMIC);
  var checkbox_margin = block.getFieldValue('margin') == 'TRUE';
  var area = checkbox_check_area;
  var pixels = checkbox_check_pixels;
  var margin = checkbox_margin;
  var merge = checkbox_check_merge.toString();
  var merge_state = merge.charAt(0).toUpperCase() + merge.slice(1);

  if (margin == false) {
    if (area == false && pixels == false) {
      var addtional_parameters = ' ';
    } else if (area == true && pixels == false) {
      var addtional_parameters = ', ' + 'area_threshold=' + value_area_threshold;
    } else if (area == false && pixels == true) {
      var addtional_parameters = ', ' + 'pixels_threshold=' + value_area_threshold;
    } else if (area == true && pixels == true) {
      var addtional_parameters = ', ' + 'pixels_threshold=' + value_area_threshold + ', area_threshold=' + value_area_threshold;
    }
  } else if (margin == true) {
    if (area == false && pixels == false) {
      var addtional_parameters = ', margin=' + value_margin;
    } else if (area == true && pixels == false) {
      var addtional_parameters = ', ' + 'area_threshold=' + value_area_threshold + ', margin=' + value_margin;
    } else if (area == false && pixels == true) {
      var addtional_parameters = ', ' + 'pixels_threshold=' + value_area_threshold + ', margin=' + value_margin;
    } else if (area == true && pixels == true) {
      var addtional_parameters = ', ' + 'pixels_threshold=' + value_area_threshold + ', area_threshold=' + value_area_threshold + ', margin=' + value_margin;
    }
  } // TODO: Assemble Python into code variable.


  var code = variable_name + '.find_blobs(' + value_color_threshold + ', roi=(' + value_xy + ',' + value_wh + '), merge=' + merge_state + addtional_parameters + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_blobs'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_get_blobs_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_detection_box_x, "x()"], [Blockly.Msg.ai_vision_detection_box_y, "y()"], [Blockly.Msg.ai_vision_detection_box_width, "w()"], [Blockly.Msg.ai_vision_detection_box_height, "h()"], [Blockly.Msg.ai_vision_detection_box_pixels, "pixels()"], [Blockly.Msg.ai_vision_detection_box_cx, "cx()"], [Blockly.Msg.ai_vision_detection_box_cy, "cy()"], [Blockly.Msg.ai_vision_detection_box_degree, "rotation()"], [Blockly.Msg.ai_vision_detection_box_total, "count()"]]), "blob_type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_get_blobs'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + type; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_qrcode'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_qrcode_.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_qrcode_detected_result);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_find_qrcode'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_qrcodes()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_qrcode_get_info'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_qrcode_get_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_pattern_detection_content, "payload"], [Blockly.Msg.ai_vision_pattern_detection_type, "data_type"], [Blockly.Msg.ai_vision_pattern_detection_x, "x"], [Blockly.Msg.ai_vision_pattern_detection_y, "y"], [Blockly.Msg.ai_vision_pattern_detection_w, "w"], [Blockly.Msg.ai_vision_pattern_detection_h, "h"]]), "get_info");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_qrcode_get_info'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_name = block.getFieldValue('get_info'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + dropdown_name + '()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_apriltag'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_apriltag_.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_apriltag_detected_result);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_find_apriltag'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_apriltags()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_apriltag_get_info'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_apriltag_get_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_pattern_detection_content, "payload"], [Blockly.Msg.ai_vision_pattern_detection_type_id, "id"], [Blockly.Msg.ai_vision_pattern_detection_type_family, "family"], [Blockly.Msg.ai_vision_pattern_detection_x, "x"], [Blockly.Msg.ai_vision_pattern_detection_y, "y"], [Blockly.Msg.ai_vision_pattern_detection_w, "w"], [Blockly.Msg.ai_vision_pattern_detection_h, "h"]]), "get_info");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_apriltag_get_info'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_name = block.getFieldValue('get_info'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + dropdown_name + '()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_datamatrices'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_datamatrix_.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_datamatrices_detected_result);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_find_datamatrices'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_datamatrices()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_datamatrices_get_info'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_data_matrices_get_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_pattern_detection_content, "payload"], [Blockly.Msg.ai_vision_pattern_detection_rows, "rows"], [Blockly.Msg.ai_vision_pattern_detection_cols, "columns"], [Blockly.Msg.ai_vision_pattern_detection_can_tolerate_count, "capacity"], [Blockly.Msg.ai_vision_pattern_detection_can_not_tolerate_count, "padding"], [Blockly.Msg.ai_vision_pattern_detection_x, "x"], [Blockly.Msg.ai_vision_pattern_detection_y, "y"], [Blockly.Msg.ai_vision_pattern_detection_w, "w"], [Blockly.Msg.ai_vision_pattern_detection_h, "h"]]), "get_info");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_datamatrices_get_info'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_name = block.getFieldValue('get_info'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + dropdown_name + '()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_barcodes'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_barcode_.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_get_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_barcode_detected_result);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_find_barcodes'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_barcodes()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_barcodes_get_info'] = {
  init: function init() {
    this.appendDummyInput().appendField("從").appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_barcode_matrices_get_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_pattern_detection_content, "payload"], [Blockly.Msg.ai_vision_pattern_detection_type, "type"], [Blockly.Msg.ai_vision_pattern_detection_x, "x"], [Blockly.Msg.ai_vision_pattern_detection_y, "y"], [Blockly.Msg.ai_vision_pattern_detection_w, "w"], [Blockly.Msg.ai_vision_pattern_detection_h, "h"]]), "get_info");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_vision_barcodes_get_info'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_name = block.getFieldValue('get_info'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + dropdown_name + '()'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_circles'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_circle.png", 50, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_find_circle);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_region_size);
    this.appendValueInput("threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_hoffman_threshold);
    this.appendValueInput("x_margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_merge_x);
    this.appendValueInput("y_margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_merge_y);
    this.appendValueInput("r_margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_merge_r);
    this.appendValueInput("r_min").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_min_radius);
    this.appendValueInput("r_max").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_max_radius);
    this.appendValueInput("r_step").setCheck(null).appendField(Blockly.Msg.ai_vision_find_circle_step_radius);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_find_circles'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var xy = Blockly.Python.valueToCode(block, 'xy', Blockly.Python.ORDER_ATOMIC);
  var wh = Blockly.Python.valueToCode(block, 'wh', Blockly.Python.ORDER_ATOMIC);
  var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  var x_margin = Blockly.Python.valueToCode(block, 'x_margin', Blockly.Python.ORDER_ATOMIC);
  var y_margin = Blockly.Python.valueToCode(block, 'y_margin', Blockly.Python.ORDER_ATOMIC);
  var r_margin = Blockly.Python.valueToCode(block, 'r_margin', Blockly.Python.ORDER_ATOMIC);
  var r_min = Blockly.Python.valueToCode(block, 'r_min', Blockly.Python.ORDER_ATOMIC);
  var r_max = Blockly.Python.valueToCode(block, 'r_max', Blockly.Python.ORDER_ATOMIC);
  var r_step = Blockly.Python.valueToCode(block, 'r_step', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_circles(roi=(' + xy + ',' + wh + '), threshold = ' + threshold + ', x_margin = ' + x_margin + ', y_margin = ' + y_margin + ', r_margin = ' + r_margin + ', r_min = ' + r_min + ', r_max = ' + r_max + ', r_step = ' + r_step + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_circles'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_find_circle_detected_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_find_circle_detected_x, "x()"], [Blockly.Msg.ai_vision_find_circle_detected_y, "y()"], [Blockly.Msg.ai_vision_find_circle_detected_radius, "r()"]]), "blob_type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_get_circles'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var type = block.getFieldValue('blob_type');
  var code = variable_name + '.' + type;
  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_lines'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_line.png", 50, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_find_line);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_find_line_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_find_line_size);
    this.appendValueInput("threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_line_hoffman_threshold);
    this.appendValueInput("theta_margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_line_merge_theta);
    this.appendValueInput("rho_margin").setCheck(null).appendField(Blockly.Msg.ai_vision_find_line_merge_rho);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_find_lines'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC);
  var theta_margin = Blockly.Python.valueToCode(block, 'theta_margin', Blockly.Python.ORDER_ATOMIC);
  var rho_margin = Blockly.Python.valueToCode(block, 'rho_margin', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_lines(roi=(' + xy + ',' + wh + '), threshold = ' + threshold + ', theta_margin = ' + theta_margin + ', rho_margin = ' + rho_margin + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_lines'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_find_line_detected_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_find_line_detected_start_x, "x1()"], [Blockly.Msg.ai_vision_find_line_detected_start_y, "y1()"], [Blockly.Msg.ai_vision_find_line_detected_end_x, "x2()"], [Blockly.Msg.ai_vision_find_line_detected_end_y, "y2()"], [Blockly.Msg.ai_vision_find_line_detected_length, "length()"], [Blockly.Msg.ai_vision_find_line_detected_angle, "theta()"]]), "blob_type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_get_lines'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + type; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_find_rects'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_vision_find_rect.png", 50, 50, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_vision_find_rect);
    this.appendValueInput("xy").setCheck(null).appendField(Blockly.Msg.ai_vision_find_rect_start_coord);
    this.appendValueInput("wh").setCheck(null).appendField(Blockly.Msg.ai_vision_find_rect_region_size);
    this.appendValueInput("threshold").setCheck(null).appendField(Blockly.Msg.ai_vision_find_rect_bounding_threshold);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_find_rects'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var threshold = Blockly.Python.valueToCode(block, 'threshold', Blockly.Python.ORDER_ATOMIC); // TODO: Assemble Python into code variable.

  var code = variable_name + '.find_rects(roi=(' + xy + ',' + wh + '), threshold = ' + threshold + ')'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_vision_get_rects'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_vision_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_vision_find_rect_detected_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_vision_find_rect_detected_tuple, "length()"], [Blockly.Msg.ai_vision_find_rect_detected_x, "x()"], [Blockly.Msg.ai_vision_find_rect_detected_y, "y()"], [Blockly.Msg.ai_vision_find_rect_detected_w, "w()"], [Blockly.Msg.ai_vision_find_rect_detected_h, "h()"]]), "blob_type");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#f0983e");
    this.setTooltip("");
    this.setHelpUrl("https://docs.singtown.com/micropython/zh/latest/openmvcam/library/omv.image.html?highlight=find_circles");
  }
};

Blockly.Python['ai_vision_get_rects'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var type = block.getFieldValue('blob_type'); // TODO: Assemble Python into code variable.

  var code = variable_name + '.' + type; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
     _    ___   __  __ _                      _                      
    / \  |_ _| |  \/  (_) ___ _ __ ___  _ __ | |__   ___  _ __   ___ 
   / _ \  | |  | |\/| | |/ __| '__/ _ \| '_ \| '_ \ / _ \| '_ \ / _ \
  / ___ \ | |  | |  | | | (__| | | (_) | |_) | | | | (_) | | | |  __/
 /_/   \_\___| |_|  |_|_|\___|_|  \___/| .__/|_| |_|\___/|_| |_|\___|
                                       |_|                           
 */


Blockly.Blocks['ai_mphone_init'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/microphone_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_microphone_init);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#5fcd8e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_mphone_init = function (block) {
  Blockly.Python.definitions_.import_all_mphone = "" + "from Maix import GPIO, I2S, FFT\n" + "from board import board_info\n" + "from fpioa_manager import fm\n" + "\n" + "sample_rate = 38640\n" + "sample_points = 1024\n" + "fft_points = 512\n" + "hist_x_num = 50\n" + "\n" + "fm.register(20,fm.fpioa.I2S0_IN_D0, force=True)\n" + "fm.register(19,fm.fpioa.I2S0_WS, force=True)\n" + "fm.register(18,fm.fpioa.I2S0_SCLK, force=True)\n" + "\n" + "_recorder_rx = I2S(I2S.DEVICE_0)\n" + "_recorder_rx.channel_config(_recorder_rx.CHANNEL_0, _recorder_rx.RECEIVER, align_mode = I2S.STANDARD_MODE)\n" + "_recorder_rx.set_sample_rate(sample_rate)\n" + "def _microphone_read_average(lst): \n" + "    return int((sum(lst)/len(lst))*100)\n" + "";
  Blockly.Python.addVariable('sample_rate', "sample_rate = 38640", true);
  Blockly.Python.addVariable('sample_points', "sample_points = 1024", true);
  Blockly.Python.addVariable('fft_points', "fft_points = 512", true);
  Blockly.Python.addVariable('hist_x_num', "hist_x_num = 50", true);
  Blockly.Python.addVariable('_recorder_rx', "", true);
  Blockly.Python.addVariable('fft_res', "", true);
  Blockly.Python.addVariable('fft_amp', "", true);
  Blockly.Python.addVariable('read_all_channel', "read_all_channel = [0, 0, 0, 0, 0, 0, 0, 0]", true); // Blockly.Python.addVariable('_recorder_rx', "", true);

  var _code = "" + "";

  return _code;
};

Blockly.Blocks['mphone_audio_spectrum_init'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/ai_audio_spectrum.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_microphone_start_spectrum_analyze);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5fcd8e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['mphone_audio_spectrum_init'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = "" + "_audio = _recorder_rx.record(sample_points)\n" + "fft_res = FFT.run(_audio.to_bytes(),fft_points)\n" + "fft_amp = FFT.amplitude(fft_res)\n\n" + "read_all_channel[0] = int(_microphone_read_average(fft_amp[0:63]))\n" + "read_all_channel[1] = int(_microphone_read_average(fft_amp[64:127]))\n" + "read_all_channel[2] = int(_microphone_read_average(fft_amp[127:191]))\n" + "read_all_channel[3] = int(_microphone_read_average(fft_amp[192:255]))\n" + "read_all_channel[4] = int(_microphone_read_average(fft_amp[256:319]))\n" + "read_all_channel[5] = int(_microphone_read_average(fft_amp[320:383]))\n" + "read_all_channel[6] = int(_microphone_read_average(fft_amp[384:447]))\n" + "read_all_channel[7] = int(_microphone_read_average(fft_amp[448:514]))\n" + "";
  return code;
};

Blockly.Blocks['ai_mphone_read_sound_sensitivity'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_microphone_get_spectrum_analyze_result).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_microphone_get_spectrum_analyze_result_1, "0"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_2, "1"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_3, "2"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_4, "3"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_5, "4"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_6, "5"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_7, "6"], [Blockly.Msg.ai_microphone_get_spectrum_analyze_result_8, "7"]]), "level");
    this.setOutput(true, null);
    this.setColour("#5fcd8e");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_mphone_read_sound_sensitivity'] = function (block) {
  var dropdown_level = block.getFieldValue('level'); // TODO: Assemble Python into code variable.

  var code = 'read_all_channel[' + dropdown_level + ']'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};
/*
     _    ___      _             _ _       
    / \  |_ _|    / \  _   _  __| (_) ___  
   / _ \  | |    / _ \| | | |/ _` | |/ _ \ 
  / ___ \ | |   / ___ \ |_| | (_| | | (_) |
 /_/   \_\___| /_/   \_\__,_|\__,_|_|\___/
*/


Blockly.Blocks['ai_audio_init'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_init);
    this.setColour("#603ea0");
    this.setTooltip("");
    this.setHelpUrl("");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
  }
};

Blockly.Python.ai_audio_init = function (block) {
  Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO";
  Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *";
  Blockly.Python.definitions_.import_audio = "import audio";
  var _code = "";
  return _code;
};

Blockly.Blocks['ai_audio_play_song'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_play_music_file);
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_play_music_file_set_vol).appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
    this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#603ea0");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_audio_play_song'] = function (block) {
  var number_play_vol = block.getFieldValue('play_vol');
  var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);

  var _in = "" + "_audio_rx = I2S(I2S.DEVICE_0)\n" + "\n" + "def _speaker_play_song(path, volume):\n" + "    global _audio_play_state\n" + "    _player = audio.Audio(path = path)\n" + "    _player.volume(volume)\n" + "    _wav_info = _player.play_process(_audio_rx)\n" + "    _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" + "    _audio_rx.set_sample_rate(_wav_info[1])\n" + "    _audio_play_state = 0\n" + "\n" + "    fm.register(34,fm.fpioa.I2S0_OUT_D1)\n" + "    fm.register(35,fm.fpioa.I2S0_SCLK)\n" + "    fm.register(33,fm.fpioa.I2S0_WS)\n" + "\n" + "    while True:\n" + "        _audio_play_state = _player.play()\n" + "        if (_audio_play_state) == True:\n" + "            print(\"Playing.\")\n" + "        elif (_audio_play_state) == False:\n" + "            print(\"Done.\")\n" + "            break\n" + "\n"; // Blockly.Python.definitions_.import_audio = _in;


  Blockly.Python.addVariable('_audio_play_state', _in, true); // Blockly.Python.addSetup("ai_audio_read", _in);

  var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n";

  return _code;
};

Blockly.Blocks['ai_audio_play_state'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_get_play_status);
    this.setOutput(true, null);
    this.setColour("#603ea0");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_audio_play_state'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_audio_play_state'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

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

Blockly.Python['ai_audio_play_finish'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_player.finish()\n';
  return code;
};

Blockly.Blocks['ai_audio_set'] = {
  init: function init() {
    this.appendValueInput("Num").setCheck(null).appendField(Blockly.Msg.ai_audio_set_music_vol);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#603ea0");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_audio_set = function (block) {
  var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);

  var _code = "_player.volume(" + _num + ")\n";

  return _code;
};
/*
             _      ___     ____                   _             
            / \    |_ _|   / ___| _ __   ___  __ _| | _____ _ __ 
           / _ \    | |    \___ \| '_ \ / _ \/ _` | |/ / _ \ '__|
          / ___ \ _ | | _   ___) | |_) |  __/ (_| |   <  __/ |   
         /_/   \_(_)___(_) |____/| .__/ \___|\__,_|_|\_\___|_|   
                                 |_|                            
*/


Blockly.Blocks['ai_audio_init_speaker'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/speaker_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_init);
    this.setColour("#5f7fc1");
    this.setTooltip("");
    this.setHelpUrl("");
    this.setPreviousStatement(true);
    this.setNextStatement(true);
  }
};

Blockly.Python.ai_audio_init_speaker = function (block) {
  Blockly.Python.definitions_.import_Maix = "from Maix import I2S, GPIO";
  Blockly.Python.definitions_.import_fpioa_manager = "from fpioa_manager import *";
  Blockly.Python.definitions_.import_audio = "import audio";
  var _code = "";
  return _code;
};

Blockly.Blocks['ai_audio_play_song_speaker'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_play_music_file);
    // this.appendDummyInput().appendField(Blockly.Msg.ai_audio_play_music_file_set_vol).appendField(new Blockly.FieldNumber(95, 0, 100, 1), "play_vol");
    this.appendValueInput("volume").setCheck(null).appendField(Blockly.Msg.ai_audio_play_music_file_set_vol);
    this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.ai_audio_play_music_file_set_file_path);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5f7fc1");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_audio_play_song_speaker'] = function (block) {
  // var number_play_vol = block.getFieldValue('play_vol');
  var number_play_vol = Blockly.Python.valueToCode(block, 'volume', Blockly.Python.ORDER_ATOMIC);
  var value_name = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);

  var _in = "" + "_audio_rx = I2S(I2S.DEVICE_0)\n" + "\n" + "def _speaker_play_song(path, volume):\n" + "    global _audio_play_state\n" + "    _player = audio.Audio(path = path)\n" + "    _player.volume(volume)\n" + "    _wav_info = _player.play_process(_audio_rx)\n" + "    _audio_rx.channel_config(_audio_rx.CHANNEL_1, I2S.TRANSMITTER, resolution = I2S.RESOLUTION_16_BIT, align_mode = I2S.STANDARD_MODE)\n" + "    _audio_rx.set_sample_rate(_wav_info[1])\n" + "    _audio_play_state = 0\n" + "\n" + "    fm.register(34,fm.fpioa.I2S0_OUT_D1)\n" + "    fm.register(35,fm.fpioa.I2S0_SCLK)\n" + "    fm.register(33,fm.fpioa.I2S0_WS)\n" + "\n" + "    while True:\n" + "        _audio_play_state = _player.play()\n" + "        if (_audio_play_state) == True:\n" + "            print(\"Playing.\")\n" + "        elif (_audio_play_state) == False:\n" + "            print(\"Done.\")\n" + "            break\n" + "\n"; // Blockly.Python.definitions_.import_audio = _in;


  Blockly.Python.addVariable('_audio_play_state', _in, true); // Blockly.Python.addSetup("ai_audio_read", _in);

  var _code = "_speaker_play_song(path=" + value_name + ", volume=" + number_play_vol + ")\n";

  return _code;
};

Blockly.Blocks['ai_audio_play_state_speaker'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_audio_get_play_status);
    this.setOutput(true, null);
    this.setColour("#5f7fc1");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_audio_play_state_speaker'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_audio_play_state'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

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

Blockly.Python['ai_audio_play_finish_speaker'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_player.finish()\n';
  return code;
};

Blockly.Blocks['ai_audio_set_speaker'] = {
  init: function init() {
    this.appendValueInput("Num").setCheck(null).appendField(Blockly.Msg.ai_audio_set_music_vol);
    this.setInputsInline(true);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#5f7fc1");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_audio_set_speaker = function (block) {
  var _num = Blockly.Python.valueToCode(block, 'Num', Blockly.Python.ORDER_ATOMIC);

  var _code = "_player.volume(" + _num + ")\n";

  return _code;
};
/*
     _    ___  __     ___     _            
    / \  |_ _| \ \   / (_) __| | ___  ___  
   / _ \  | |   \ \ / /| |/ _` |/ _ \/ _ \ 
  / ___ \ | |    \ V / | | (_| |  __/ (_) |
 /_/   \_\___|    \_/  |_|\__,_|\___|\___/ 
*/


Blockly.Blocks['ai_video_record_setup'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/video_record_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_start_recording);
    this.appendValueInput("save_path").setCheck(null).appendField(Blockly.Msg.ai_video_start_recording_file_path);
    this.appendValueInput("w").setCheck(null).appendField(Blockly.Msg.ai_video_start_recording_width);
    this.appendValueInput("h").setCheck(null).appendField(Blockly.Msg.ai_video_start_recording_height);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_video_record_setup'] = function (block) {
  var value_save_path = Blockly.Python.valueToCode(block, 'save_path', Blockly.Python.ORDER_ATOMIC);
  var value_w = Blockly.Python.valueToCode(block, 'w', Blockly.Python.ORDER_ATOMIC);
  var value_h = Blockly.Python.valueToCode(block, 'h', Blockly.Python.ORDER_ATOMIC);
  Blockly.Python.definitions_.import_video = "import video";
  Blockly.Python.definitions_.import_Maix = "from Maix import GPIO";
  Blockly.Python.addVariable('record_vid', 'record_vid = None', true); // TODO: Assemble Python into code variable.

  var code = "_record_vid = video.open(" + value_save_path + ", record=1, width=" + value_w + ", height=" + value_h + ", interval=20000, quality=80)\n";
  return code;
};

Blockly.Blocks['ai_video_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_to_canvas).appendField(new Blockly.FieldVariable("canvas"), "varitem").appendField(Blockly.Msg.ai_video_record);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#60c1bb");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_video_get = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);

  var _code = "_record_vid.record(" + variable_name + ")\n";

  return _code;
};

Blockly.Blocks['ai_video_stop'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_stop_recording);
    this.setPreviousStatement(true);
    this.setNextStatement(true);
    this.setColour("#60c1bb");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_video_stop = function (block) {
  var _code = "_record_vid.record_finish()\n";
  return _code;
};

Blockly.Blocks['ai_video_set'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/video_init_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_play_video);
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_play_video_2);
    this.appendValueInput("path").setCheck(null).appendField(Blockly.Msg.ai_video_play_video_file_path);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#4d9994");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_video_set'] = function (block) {
  Blockly.Python.definitions_.import_video = "import video";
  Blockly.Python.definitions_.import_Maix = "from Maix import GPIO";
  Blockly.Python.addVariable('_video_play', '', true);
  var value_path = Blockly.Python.valueToCode(block, 'path', Blockly.Python.ORDER_ATOMIC);
  var code = '_video_play = video.open(' + value_path + ')\n';
  return code;
};

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

Blockly.Python['ai_video_stop_play'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = '_video_play.__del__()\n';
  return code;
};

Blockly.Blocks['ai_video_status'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_video_get_video_playing_status);
    this.setOutput(true, null);
    this.setColour("#4d9994");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_video_status = function (block) {
  var code = "_video_play.play()";
  return [code, Blockly.Python.ORDER_NONE];
};
/*
     _    ___   __  __           _      _     
    / \  |_ _| |  \/  | ___   __| | ___| |___ 
   / _ \  | |  | |\/| |/ _ \ / _` |/ _ \ / __|
  / ___ \ | |  | |  | | (_) | (_| |  __/ \__ \
 /_/   \_\___| |_|  |_|\___/ \__,_|\___|_|___/

*/


Blockly.Blocks['ai_model_allinit'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_title).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_models_init_hand_written_model, "Single Digit Recognition"], [Blockly.Msg.ai_models_init_object_model, "Common Object Recognition"], [Blockly.Msg.ai_models_init_face_model, "Human Face Recognition"]]), "DEGREE");
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_init_source).appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#ee783a");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_model_allinit = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
  var degee = block.getFieldValue('DEGREE');
  var _code = "";

  if (degee == "Single Digit Recognition") {
    Blockly.Python.addVariable('task_mnist', "task_mnist = kpu.load(\"/sd/preset/models/mnist.kmodel\")\n", true); // Blockly.Python.addVariable('img_mnist1', '', true);
    // Blockly.Python.addVariable('img_mnist_resized', '', true);

    _code += "img_mnist1=img_mnist.to_grayscale(1)\n";
    _code += "img_mnist_resized=img_mnist1.resize(28,28)\n";
    _code += "a=img_mnist_resized.invert()\n";
    _code += "a=img_mnist_resized.strech_char(1)\n";
    _code += "a=img_mnist_resized.pix_to_ai()\n";
    _code += "fmap_mnist=kpu.forward(task_mnist, " + variable_name + ")\n";
    _code += "plist_mnist=fmap_mnist[:]\n";
    _code += "pmax_mnist=max(plist_mnist)\n";
    _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n";
  } else if (degee == "Common Object Recognition") {
    Blockly.Python.addVariable('task_objectrecognition', '', true);
    Blockly.Python.addVariable('img_objectrecognition', '' + 'classes_objectrecognition = [\'aeroplane\', \'bicycle\', \'bird\', \'boat\', \'bottle\', \'bus\', \'car\', \'cat\', \'chair\', \'cow\', \'diningtable\', \'dog\', \'horse\', \'motorbike\', \'person\', \'pottedplant\', \'sheep\', \'sofa\', \'train\', \'tvmonitor\']\n' + 'task_objectrecognition = kpu.load("/sd/preset/models/tinyyolo_v2_20class.kmodel")\n' + 'object_anchor = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n' + 'a = kpu.init_yolo2(task_objectrecognition, 0.5, 0.3, 5, object_anchor)\n' + '', true); // Blockly.Python.addVariable('code_objectrecognition', '', true);

    _code += "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n";
    _code += variable_name + ".ai_to_pix()\n";
  } else {
    Blockly.Python.addVariable('task_facerecognition', '', true); // Blockly.Python.addVariable('task_facerecognition', '', true);

    Blockly.Python.addVariable('img_facerecognition', "" + "task_facerecognition = kpu.load(\"/sd/preset/models/preset/face-recognition.kmodel\")\n" + "anchor_face = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n" + "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor_face)\n" + "\n", true); // Blockly.Python.addVariable('code_facerecognition', '', true);

    _code += "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n";
    _code += variable_name + ".ai_to_pix()\n";
  }

  return _code;
};

Blockly.Blocks['ai_model_index_mnist'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/digit_recognition_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_hand_written_model_result);
    this.appendDummyInput().appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_models_hand_written_model_number, "c"], [Blockly.Msg.ai_models_hand_written_model_confidence, "confidence"]]), "value");
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip('');
    this.setHelpUrl('');
  }
};

Blockly.Python.ai_model_index_mnist = function (block) {
  var value = block.getFieldValue('value');
  var _code = "max_index_mnist";

  if (value == "confidence") {
    _code = "int(pmax_mnist*100)";
  }

  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_model_look'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_object_model_if);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_model_look = function (block) {
  var _code = "code_objectrecognition";
  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_model_get'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/object_recognition_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_models_object_model_get).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_models_object_model_name, "Object"], [Blockly.Msg.ai_models_object_model_x, "X"], [Blockly.Msg.ai_models_object_model_y, "Y"], [Blockly.Msg.ai_models_object_model_w, "W"], [Blockly.Msg.ai_models_object_model_h, "H"], [Blockly.Msg.ai_models_object_model_count, "Number"], [Blockly.Msg.ai_models_object_model_index, "Serial"], [Blockly.Msg.ai_models_object_model_confidence, "Confidence"]]), "TYPE");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_model_get = function (block) {
  var type = block.getFieldValue('TYPE');
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var _code = "";

  if (type == "Object") {
    _code = "classes_objectrecognition[" + variable_name + ".classid()]";
  } else if (type == "X") {
    _code = variable_name + ".x()";
  } else if (type == "Y") {
    _code = variable_name + ".y()";
  } else if (type == "W") {
    _code = variable_name + ".w()";
  } else if (type == "H") {
    _code = variable_name + ".h()";
  } else if (type == "Number") {
    _code = variable_name + ".objnum()";
  } else if (type == "Serial") {
    _code = variable_name + ".index()";
  } else if (type == "Confidence") {
    _code = variable_name + ".value()";
  }

  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_model_face'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_face_model_if);
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_model_face = function (block) {
  var _code = "code_facerecognition";
  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_model_xy'] = {
  init: function init() {
    this.appendDummyInput().appendField(new Blockly.FieldImage("blockly/media/face_recognition_header.png", 45, 45, {
      alt: "*",
      flipRtl: "FALSE"
    }));
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_models_face_model_get).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_models_face_model_x, "X"], [Blockly.Msg.ai_models_face_model_y, "Y"], [Blockly.Msg.ai_models_face_model_w, "W"], [Blockly.Msg.ai_models_face_model_h, "H"], [Blockly.Msg.ai_models_face_model_count, "Number"], [Blockly.Msg.ai_models_face_model_index, "Serial"], [Blockly.Msg.ai_models_face_model_confidence, "Confidence"]]), "TYPE");
    this.setInputsInline(false);
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_model_xy = function (block) {
  var type = block.getFieldValue('TYPE');
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var _code = "";

  if (type == "X") {
    _code = variable_name + ".x()";
  } else if (type == "Y") {
    _code = variable_name + ".y()";
  } else if (type == "W") {
    _code = variable_name + ".w()";
  } else if (type == "H") {
    _code = variable_name + ".h()";
  } else if (type == "Number") {
    _code = variable_name + ".objnum()";
  } else if (type == "Serial") {
    _code = variable_name + ".index()";
  } else if (type == "Confidence") {
    _code = variable_name + ".value()";
  }

  return [_code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Blocks['ai_model_customized_init_setup'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_customized_init_setup_title);
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_customized_init_setup_path).appendField(new Blockly.FieldTextInput("/sd/user/mymodel.kmodel"), "model_path");
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_customized_init_setup_source).appendField(new Blockly.FieldVariable("camera"), "varitem");
    this.appendValueInput("class_input").setCheck(null).appendField(Blockly.Msg.ai_models_customized_init_setup_name);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_model_customized_init_setup'] = function (block) {
  var value_class_input = Blockly.Python.valueToCode(block, 'class_input', Blockly.Python.ORDER_ATOMIC);
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var text_model_path = block.getFieldValue('model_path');
  Blockly.Python.definitions_.import_KPU_customized = "import KPU as kpu";
  Blockly.Python.addVariable('task_customized_model', '' + 'task_customized_model = kpu.load("' + text_model_path + '")\n' + 'anchor_customized_model = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828)\n' + 'a = kpu.init_yolo2(task_customized_model, 0.6, 0.3, 5, anchor_customized_model)\n' + '', true);
  Blockly.Python.addVariable('classes_customized_model', '' + 'classes_customized_model = ' + value_class_input + '\n' + '', true);
  var code = 'code_customized_model = kpu.run_yolo2(task_customized_model, ' + variable_name + ')\n';
  return code;
};

Blockly.Blocks['ai_model_customized_if_got'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_customized_if_got);
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_model_customized_if_got'] = function (block) {
  // TODO: Assemble Python into code variable.
  var code = 'code_customized_model'; // TODO: Change ORDER_NONE to the correct strength.

  return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['ai_model_customized_get_result'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_models_from).appendField(new Blockly.FieldVariable("i"), "varitem").appendField(Blockly.Msg.ai_models_customized_get_result_any).appendField(new Blockly.FieldDropdown([[Blockly.Msg.ai_models_customized_get_result_name, "classid"], [Blockly.Msg.ai_models_customized_get_result_x, "x"], [Blockly.Msg.ai_models_customized_get_result_y, "y"], [Blockly.Msg.ai_models_customized_get_result_w, "w"], [Blockly.Msg.ai_models_customized_get_result_h, "h"], [Blockly.Msg.ai_models_customized_get_result_count, "objnum"], [Blockly.Msg.ai_models_customized_get_result_index, "index"], [Blockly.Msg.ai_models_customized_get_result_confidence, "value"]]), "get_results");
    this.setOutput(true, null);
    this.setColour("#ee783a");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python['ai_model_customized_get_result'] = function (block) {
  var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
  var dropdown_get_results = block.getFieldValue('get_results'); // TODO: Assemble Python into code variable.

  if (dropdown_get_results == "classid") {
    var code = 'classes_customized_model[' + variable_name + '.classid()]';
  } else {
    var code = variable_name + '.' + dropdown_get_results + '()';
  } // TODO: Change ORDER_NONE to the correct strength.


  return [code, Blockly.Python.ORDER_NONE];
};
/*

Blockly.Blocks['ai_model_init'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.MODELLPM)
            .appendField(new Blockly.FieldDropdown([
                ["Single Digit Recognition", "Single Digit Recognition"],
                ["Common Object Recognition", "Common Object Recognition"],
                ["Animal Recognition", "Animal Recognition"],
                ["Human Face Recognition", "Human Face Recognition"]
            ]), "DEGREE")
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_init = function(block) {
    Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
    var degee = block.getFieldValue('DEGREE');
    var _code = ""
    if (degee == "Single Digit Recognition") {
        _code += "task_mnist = kpu.load(\"/sd/models/mnist.kmodel\")\n";
    } else if (degee == "Common Object Recognition") {
        _code += "classes_animalrecognition = ['aeroplane', 'bicycle', '', 'boat', 'bottle', 'bus', 'car', '', 'chair', '', 'diningtable', '', '', 'motorbike', 'person', 'pottedplant', '', 'sofa', 'train', 'tvmonitor']\n";
        _code += "task_animalrecognition = kpu.load(\"/sd/models/object-recognition.kmodel\")\n";
        _code += "anchor_animalrecognition = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n";
        _code += "a = kpu.init_yolo2(task_animalrecognition, 0.5, 0.3, 5, anchor_animalrecognition)\n";
    } else if (degee == "Animal Recognition") {
        _code += "classes_animalrecognition = ['', '', 'bird', '', '', '', '', 'cat', '', 'cow', '', 'dog', 'horse', '', '', '', 'sheep', '', '', '']\n";
        _code += "task_animalrecognition = kpu.load(\"/sd/models/animal-recognition.kmodel\")\n";
        _code += "anchor_animalrecognition = (1.08, 1.19, 3.42, 4.41, 6.63, 11.38, 9.42, 5.11, 16.62, 10.52)\n";
        _code += "a = kpu.init_yolo2(task_animalrecognition, 0.5, 0.3, 5, anchor_animalrecognition)\n";
    } else {
        _code += "task_facerecognition = kpu.load(\"/sd/models/face-recognition.kmodel\")\n";
        _code += "anchor = (1.889, 2.5245, 2.9465, 3.94056, 3.99987, 5.3658, 5.155437, 6.92275, 6.718375, 9.01025)\n";
        _code += "a = kpu.init_yolo2(task_facerecognition, 0.5, 0.3, 5, anchor)\n";
    }
    return _code;
}


Blockly.Blocks['ai_model_img_mnist'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIT);
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIT_SISF)
            .appendField(new Blockly.FieldVariable("img_mnist"), "varitem");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_img_mnist = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var _code = "img_mnist1=" + variable_name + ".to_grayscale(1)\n"
    _code += "img_mnist2=img_mnist1.resize(28,28)\n"
    _code += "a=img_mnist2.invert()\n"
    _code += "a=img_mnist2.strech_char(1)\n"
    _code += "a=img_mnist2.pix_to_ai()\n"
    _code += "fmap_mnist=kpu.forward(task_mnist,img_mnist2)\n"
    _code += "plist_mnist=fmap_mnist[:]\n"
    _code += "pmax_mnist=max(plist_mnist)\n"
    _code += "max_index_mnist=plist_mnist.index(pmax_mnist)\n"
    return _code;
}

*/

/*

Blockly.Blocks['ai_model_pmax_mnist'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIT_FPM)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIT_GTCS)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_pmax_mnist = function(block) {
    var _code = "int(pmax_mnist*100)\n"
    return _code;
}

Blockly.Blocks['ai_model_objectrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_SMSFIOR)
            .appendField(new Blockly.FieldVariable("img_objectrecognition"), "varitem");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_objectrecognition = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var _code = "code_objectrecognition = kpu.run_yolo2(task_objectrecognition, " + variable_name + ")\n"
    return _code;
}

Blockly.Blocks['ai_model_aobjectrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_ACOID)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_aobjectrecognition = function(block) {
    var _code = "code_objectrecognition\n"
    return _code;
}


Blockly.Blocks['ai_model_ifaobjectrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.OLCD_SETROTATION)
            .appendField(new Blockly.FieldDropdown([
                ["0°", "1"],
                ["90°", "2"],
                ["180°", "3"],
                ["270°", "0"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_ifaobjectrecognition = function(block) {
    // if code_objectrecognition:        # if object is detected then do
    // for i_objectrecognition in code_objectrecognition:
    //     # ...
    var _code = "code_objectrecognition\n"
    return _code;
}


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

        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_G)
            .appendField(new Blockly.FieldDropdown([
                ["X-Coordinate", "x"],
                ["Y-Coordinate", "y"],
                ["Width of the Detection Box", "w"],
                ["Height of the Detection Box", "h"],
                ["Number of Objects Detected", "objnum"],
                ["Index of Object Detected", "index"],
                ["Confidence Score (%)", "value"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.CAMERINITPM_GIOTCOD)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_xyobjectreocgnition = function(block) {
    var degee = block.getFieldValue('DEGREE');
    var _code = "i_objectreocgnition." + degee + "()\n"
    return _code;
}

Blockly.Blocks['ai_model_cobjectrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_DCOIA)
            .appendField(new Blockly.FieldDropdown([
                ["Aeroplane", "Aeroplane"],
                ["Bicycle", "Bicycle"],
                ["Boat", "Boat"],
                ["Bus", "Bus"],
                ["Car", "Car"],
                ["Chair", "Chair"],
                ["Dining", "Dining"],
                ["Table", "Table"],
                ["Motorbike", "Motorbike"],
                ["Person", "Person"],
                ["Potted", "Potted"],
                ["Plant", "Plant"],
                ["Sofa", "Sofa"],
                ["Train", "Train"],
                ["Monitor", "Monitor"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_cobjectrecognition = function(block) {
    var degee = block.getFieldValue('DEGREE');
    var _code = "classes_objectrecognition[i.classid()]\n"
    return _code;
}




Blockly.Blocks['ai_model_animalrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMA)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_SMSFIOR)
            .appendField(new Blockly.FieldVariable("img_animalrecognition"), "varitem");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_animalrecognition = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var _code = "code_animalrecognition = kpu.run_yolo2(task_animalrecognition, " + variable_name + ")\n"
    return _code;
}

Blockly.Blocks['ai_model_aanimalrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMA_AAOID)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_aanimalrecognition = function(block) {
    var _code = "code_animalrecognition\n"
    return _code;
}

Blockly.Blocks['ai_model_ifanimalrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.OLCD_SETROTATION)
            .appendField(new Blockly.FieldDropdown([
                ["0°", "1"],
                ["90°", "2"],
                ["180°", "3"],
                ["270°", "0"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_ifanimalrecognition = function(block) {
    // if code_animalrecognition:        # if object is detected then do
    // for i_animalrecognition in code_animalrecognition:
    //     # ...



    var _code = "code_objectrecognition\n"
    return _code;
}



Blockly.Blocks['ai_model_xyanimalrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMA_FPMA)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_G)
            .appendField(new Blockly.FieldDropdown([
                ["X-Coordinate", "x"],
                ["Y-Coordinate", "y"],
                ["Width of the Detection Box", "w"],
                ["Height of the Detection Box", "h"],
                ["Number of Objects Detected", "objnum"],
                ["Index of Object Detected", "index"],
                ["Confidence Score (%)", "value"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.CAMERINITPMA_GIOTCAD)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_xyanimalrecognition = function(block) {
    var degee = block.getFieldValue('DEGREE');
    var _code = "i_animalrecognition." + degee + "()\n"
    return _code;
}


Blockly.Blocks['ai_model_canimalrecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMA_DAOIA)
            .appendField(new Blockly.FieldDropdown([
                ["Bird", "Bird"],
                ["Cat", "Cat"],
                ["Cow", "Cow"],
                ["Dog", "Dog"],
                ["Horse", "Horse"],
                ["Sheep", "Sheep"]
            ]), "DEGREE")
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_canimalrecognition = function(block) {
    var degee = block.getFieldValue('DEGREE');
    var _code = "classes_animalrecognition[i.classid()]\n"
    return _code;
}

Blockly.Blocks['ai_model_facerecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_SISFIF)
            .appendField(new Blockly.FieldVariable("img_facerecognition"), "varitem");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_facerecognition = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var _code = "code_facerecognition = kpu.run_yolo2(task_facerecognition, " + variable_name + ")\n"
    return _code;
}

Blockly.Blocks['ai_model_afacerecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_AFID)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_afacerecognition = function(block) {
    var _code = "code_facerecognition\n"
    return _code;
}

Blockly.Blocks['ai_model_iffacerecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.OLCD_SETROTATION)
            .appendField(new Blockly.FieldDropdown([
                ["0°", "1"],
                ["90°", "2"],
                ["180°", "3"],
                ["270°", "0"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_iffacerecognition = function(block) {
    // if code_facerecognition:        # if face is detected then do
    // for i_facerecognition in code_facerecognition:
    //     # ...



    var _code = "code_objectrecognition\n"
    return _code;
}

Blockly.Blocks['ai_model_xyfacerecognition'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_FPM)
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPM_G)
            .appendField(new Blockly.FieldDropdown([
                ["X-Coordinate", "x"],
                ["Y-Coordinate", "y"],
                ["Width of the Detection Box", "w"],
                ["Height of the Detection Box", "h"],
                ["Number of Objects Detected", "objnum"],
                ["Index of Object Detected", "index"],
                ["Confidence Score (%)", "value"]
            ]), "DEGREE")
            .appendField(Blockly.Msg.CAMERINITPMF_GIOTFD)
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_xyfacerecognition = function(block) {
    var degee = block.getFieldValue('DEGREE');
    var _code = "i_facerecognition." + degee + "()\n"
    return _code;
}

Blockly.Blocks['ai_model_kpuload'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_LCMLM);
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_FSC)
            .appendField(new Blockly.FieldTextInput("/sd/models/facedetect.kmodel"), "input")
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_kpuload = function(block) {
    var input = block.getFieldValue('input');
    Blockly.Python.definitions_.import_KPU = "import KPU as kpu";
    var _code = "kpu.load(\"" + input + "\")\n"
    return _code;
}


Blockly.Blocks['ai_model_inityolo2'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIINNYFNOT)
            .appendField(Blockly.Msg.CAMERINIINNYFNOT_F)
            .appendField(new Blockly.FieldVariable("task"), "varitem");

        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINIINNYFNOT_SPT)
            .appendField(new Blockly.FieldTextInput("0"), "input")
            .appendField(Blockly.Msg.CAMERINIINNYFNOT_SPT_S)
            .appendField(new Blockly.FieldTextInput("0"), "input1");

        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERINITPMF_SNOAA)
            .appendField(new Blockly.FieldTextInput("5"), "input2")
            .appendField(Blockly.Msg.CAMERINITPMF_SNOAA_S)
            .appendField(new Blockly.FieldVariable("anchor"), "varitem1");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_inityolo2 = function(block) {
    var varitem = block.getFieldValue('varitem');
    var varitem1 = block.getFieldValue('varitem1');
    var input = block.getFieldValue('input');
    var input1 = block.getFieldValue('input1');
    var input2 = block.getFieldValue('input2');
    var _code = "kpu.init_yolo2(" + varitem + ", " + input + ", " + input1 + ", " + input2 + ", " + varitem1 + ")\n"
    return _code;
}


Blockly.Blocks['ai_model_runyolo2'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGRFRNNY);
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGRFRNNY_FNOT)
            .appendField(new Blockly.FieldVariable("task"), "varitem");
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGRFRNNY_SISA)
            .appendField(new Blockly.FieldVariable("camera"), "varitem1");
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_runyolo2 = function(block) {
    var varitem = block.getFieldValue('varitem');
    var varitem1 = block.getFieldValue('varitem1');
    var _code = "kpu.run_yolo2(" + varitem + ", " + varitem1 + ")\n"
    return _code;
}

Blockly.Blocks['ai_model_forward'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGFMOFNOT)
            .appendField(new Blockly.FieldVariable("task"), "varitem")
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGFMOFNOT_SISAC)
            .appendField(new Blockly.FieldTextInput("3"), "input")
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERGFMOFNOT_SISAC)
            .appendField(new Blockly.FieldVariable("task"), "varitem1")
        this.setOutput(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_forward = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var variable_name1 = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem1'), Blockly.Variables.NAME_TYPE);
    var input = block.getFieldValue('input');
    var _code = "kpu.forward(" + variable_name + "," + variable_name1 + "," + input + ")\n"
    return _code;
}

Blockly.Blocks['ai_model_deinit'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CAMERDNOT)
            .appendField(new Blockly.FieldVariable("task"), "varitem")
            .appendField(Blockly.Msg.OLCD_SETROTATION_DEGREE)
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour("#ee783a");
        this.setTooltip('');
        this.setHelpUrl('');
    }
};

Blockly.Python.ai_model_deinit = function(block) {
    var variable_name = Blockly.Python.variableDB_.getName(block.getFieldValue('varitem'), Blockly.Variables.NAME_TYPE);
    var _code = "kpu.deinit(" + variable_name + ")\n"
    return _code;
}

Blockly.Blocks['ai_vision_if'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_IF)
            .appendField(new Blockly.FieldDropdown([
                ["Red", "fcr_threshold_red"],
                ["Green", "fcr_threshold_green"],
                ["Blue", "fcr_threshold_blue"]
            ]), "color")
            .appendField(Blockly.Msg.VISION_IF_R)
            .appendField(new Blockly.FieldVariable("img"), "varitem");
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_IF_S)
            .appendField(new Blockly.FieldTextInput("60"), "input")
            .appendField(Blockly.Msg.HID_MOUSE_MOVE_DISTANCE);
        this.appendStatementInput('DO0')
            .appendField(Blockly.Msg.TOUCH_DO);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#f2a247");
    }
};

Blockly.Python.ai_vision_if = function(block) {
    var input = block.getFieldValue('input');
    var varitem = block.getFieldValue('varitem');
    var color = block.getFieldValue('color');
    Blockly.Python.addVariable('fcr_threshold_red', 'fcr_threshold_red = (30, 100, 15, 127, 15, 127)', true);
    Blockly.Python.addVariable('fcr_threshold_green', 'fcr_threshold_green = (30, 100, -64, -8, -32, 32)', true);
    Blockly.Python.addVariable('fcr_threshold_blue', 'fcr_threshold_blue = (45, 65, -20, 30, -60, -20)', true);
    Blockly.Python.addVariable('fcr_current_threshold', 'fcr_current_threshold = ' + color, true);
    Blockly.Python.addVariable('fcr_max_region_size_detected', 'fcr_max_region_size_detected = ' + input, true);
    var _code = "fcr_blobs = " + varitem + ".find_blobs([fcr_current_threshold], area_threshold=150)\n"
    _code += "    if fcr_blobs:    \n"
    _code += "        for b in fcr_blobs:\n"
    _code += "            if (b[2] > fcr_max_region_size_detected) or ((b[3] > fcr_max_region_size_detected)):\n"
    _code += "                " + varitem + ".draw_rectangle(b[0:4])\n"
    _code += "                " + varitem + ".draw_cross(b[5], b[6])\n"
    _code += "                " + varitem + ".draw_rectangle(b[0], b[1]-20, b[2], 20, color=(255,255,255), fill=True)\n"
    _code += "                " + varitem + ".draw_string(b[0]+2, b[1]-20+2, \"x:\"+ str(b[0]) + \", y:\"+ str(b[1]), mono_space=False, color=(0,0,0), scale=2)\n"
    return _code;
}

Blockly.Blocks['ai_vision_gd'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_IF_C)
            .appendField(new Blockly.FieldDropdown([
                ["X Coordinate", "0"],
                ["Y Coordinate", "1"],
                ["Width", "2"],
                ["Height", "3"],
            ]), "dropdown");
        this.setOutput(true, null);
        this.setColour("#f2a247");
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python.ai_vision_gd = function(block) {
    var d = block.getFieldValue('dropdown');
    var _code = "b[" + d + "]\n"
    return _code;
}

Blockly.Blocks['ai_vision_dif'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.CONTROLS_IF_MSG_IF)
            .appendField(new Blockly.FieldDropdown([
                ["Red", "fcr_threshold_red"],
                ["Green", "fcr_threshold_green"],
                ["Blue", "fcr_threshold_blue"]
            ]), "color")
            .appendField(Blockly.Msg.VISION_CIF)
            .appendField(new Blockly.FieldVariable("img"), "varitem");
        this.appendStatementInput('DO0')
            .appendField(Blockly.Msg.TOUCH_DO);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#f2a247");
    }
};

Blockly.Python.ai_vision_dif = function(block) {
    var color = block.getFieldValue('color');
    var varitem = block.getFieldValue('varitem');
    Blockly.Python.addVariable('fc_threshold_red', 'fc_threshold_red = (30, 100, 15, 127, 15, 127)', true);
    Blockly.Python.addVariable('fc_threshold_green', 'fc_threshold_green = (30, 100, -64, -8, -32, 32)', true);
    Blockly.Python.addVariable('fc_threshold_blue', 'fc_threshold_blue = (45, 65, -20, 30, -60, -20)', true);
    Blockly.Python.addVariable('fc_color_threshold', 'fc_color_threshold = ' + color, true);
    Blockly.Python.addVariable('fc_bounding_box_color', 'fc_bounding_box_color = (200,200,200)', true);
    var _code = "def fc_expand_roi(roi):\n"
    _code += "    extra = 5\n"
    _code += "    win_size = (224, 224)\n"
    _code += "    (x, y, width, height) = roi\n"
    _code += "    fc_new_roi = [x-extra, y-extra, width+2*extra, height+2*extra]\n"
    _code += "\n"
    _code += "    if fc_new_roi[0] < 0:\n"
    _code += "        fc_new_roi[0] = 0\n"
    _code += "    if fc_new_roi[1] < 0:\n"
    _code += "        fc_new_roi[1] = 0\n"
    _code += "    if fc_new_roi[2] > win_size[0]:\n"
    _code += "        fc_new_roi[2] = win_size[0]\n"
    _code += "    if fc_new_roi[3] > win_size[1]:\n"
    _code += "        fc_new_roi[3] = win_size[1]\n"
    _code += "\n"
    _code += "    return tuple(fc_new_roi)\n"
    Blockly.Python.addFunction("fc_expand_roi", _code);

    _code = "fc_blobs = " + varitem + ".find_blobs([fc_color_threshold], area_threshold=150)\n"
    "    if fc_blobs:\n"
    "        for fc_blob in fc_blobs:\n"
    "            fc_is_circle = False\n"
    "            fc_max_circle = None\n"
    "            fc_max_radius = -1\n"
    "            fc_new_roi = fc_expand_roi(fc_blob.rect())\n"
    "\n"
    "            for fc_c in " + varitem + ".find_circles(threshold = 2000, x_margin = 20, y_margin = 20, r_margin = 10, roi=fc_new_roi):\n"
    "                fc_is_circle = True\n"
    "                # " + varitem + ".draw_circle(c.x(), c.y(), c.r(), color = (255, 255, 255))\n"
    "                if fc_c.r() > fc_max_radius:\n"
    "                    fc_max_radius = fc_c.r()\n"
    "                    fc_max_circle = fc_c\n"

    "           if fc_is_circle:\n"
    "                " + varitem + ".draw_rectangle(fc_new_roi, thickness=1)\n"
    "                " + varitem + ".draw_rectangle(fc_new_roi[0], fc_new_roi[1]-20, fc_new_roi[2], 20, color=(255,255,255), fill=True)\n"
    "                " + varitem + ".draw_string(fc_new_roi[0]+2, fc_new_roi[1]-20+2, \"x:\"+ str(fc_new_roi[0]) + \", y:\"+ str(fc_new_roi[1]), mono_space=False, color=(0,0,0), scale=2)\n"
    "                " + varitem + ".draw_cross(fc_blob[5], fc_blob[6])\n"
    "                " + varitem + ".draw_circle(fc_max_circle.x(), fc_max_circle.y(), fc_max_circle.r(), color = fc_bounding_box_color)\n"
    "                " + varitem + ".draw_circle(fc_max_circle.x(), fc_max_circle.y(), fc_max_circle.r() + 1, color = fc_bounding_box_color)\n"
    return _code;
}

Blockly.Blocks['ai_vision_dgd'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_CIF_D)
            .appendField(new Blockly.FieldDropdown([
                ["X Coordinate", "0"],
                ["Y Coordinate", "1"],
                ["Width", "2"],
                ["Height", "3"],
            ]), "dropdown");
        this.setOutput(true, null);
        this.setColour("#f2a247");
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python.ai_vision_dgd = function(block) {
    var n = block.getFieldValue('dropdown');
    var _code = "fc_new_roi[" + n + "]\n"
    return _code;
}

Blockly.Blocks['ai_vision_sif'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_SIF);
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_SIF_D)
            .appendField(new Blockly.FieldDropdown([
                ["Black", "DETECT_SINGLE_BLACK_LINE"],
                ["White", "DETECT_SINGLE_WHITE_LINE"]
            ]), "color")
        this.appendStatementInput('DO0')
            .appendField(Blockly.Msg.TOUCH_DO);
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setColour("#f2a247");
    }
};

Blockly.Python.ai_vision_sif = function(block) {
    var color = block.getFieldValue('color');
    Blockly.Python.addVariable('ROI', "ROI = (0, 92, 224, 40)", true);
    Blockly.Python.addVariable('DETECT_SINGLE_BLACK_LINE', "[(0, 40)]", true);
    Blockly.Python.addVariable('DETECT_SINGLE_WHITE_LINE', "[(128, 255)]", true);
    Blockly.Python.addVariable('GRAYSCALE_THRESHOLD', "ROI = " + color, true);
    var _code = "def get_blob_value(blob):\n";
    _code += "    return blob.w()\n";
    Blockly.Python.addFunction("get_blob_value", _code);

    _code = "def compare_blob(blob1, blob2):\n"
    _code += "    comp_result = get_blob_value(blob1) - get_blob_value(blob2)\n"
    _code += "    if comp_result > 3:\n"
    _code += "        return 1\n"
    _code += "    elif comp_result < -3:\n"
    _code += "        return -1\n"
    _code += "    else:\n"
    _code += "        return 0\n"
    Blockly.Python.addFunction("compare_blob", _code);

    _code = "def get_direction(left_blob, right_blob):\n"
    _code += "    MAX_WIDTH = 224\n"
    _code += "    theta = 0.01\n"
    _code += "    b = 3\n"
    _code += "    x1 = left_blob.x() - int(0.5 * left_blob.w())\n"
    _code += "    x2 = right_blob.x() + int(0.5 * right_blob.w())\n"
    _code += "    w_left = x1\n"
    _code += "    w_center = math.fabs(x2 - x1)\n"
    _code += "    w_right = math.fabs(MAX_WIDTH - x2)\n"
    _code += "    direct_ratio = (w_left + b + theta * w_center) / (w_left + w_right + 2 * b + 2 * theta * w_center) - 0.5\n"
    _code += "    return direct_ratio\n"
    Blockly.Python.addFunction("get_direction", _code);

    _code = "def get_top2_blobs(blobs):\n"
    _code += "    for blob in blobs:\n"
    _code += "        pass\n"
    _code += "        #print(blob)\n"
    _code += "        # img.draw_rectangle(blob.rect())\n"
    _code += "    if len(blobs) < 2:\n"
    _code += "        return (None, None)\n"
    _code += "    top_blob1 = blobs[0]\n"
    _code += "    top_blob2 = blobs[1]\n"
    _code += "    if compare_blob(top_blob1, top_blob2) == -1:\n"
    _code += "        top_blob1, top_blob2 = top_blob2, top_blob1\n"
    _code += "    for i in range(2, len(blobs)):\n"
    _code += "        if compare_blob(blobs[i], top_blob1) == 1:\n"
    _code += "            top_blob2 = top_blob1\n"
    _code += "            top_blob1 = blobs[i]\n"
    _code += "        elif compare_blob(blobs[i], top_blob2) == 1:\n"
    _code += "            top_blob2 = blobs[i]\n"
    _code += "    if top_blob1.cx() > top_blob2.cx():\n"
    _code += "        return (top_blob2, top_blob1)\n"
    _code += "    else:\n"
    _code += "        return (top_blob1, top_blob2)\n"
    Blockly.Python.addFunction("get_top2_blobs", _code);

    _code = "def draw_direct(img, direct_ratio):\n"
    _code += "    img.draw_circle(112, 112, 5)\n"
    _code += "    img.draw_line((112, 112, int(112 + direct_ratio * 20), 112))\n"
    Blockly.Python.addFunction("draw_direct", _code);


    // # b 積木主體代碼
    _code = "img = sensor.snapshot()";
    _code += "blobs = img.find_blobs(GRAYSCALE_THRESHOLD, roi = ROI, merge = True)";
    _code += "if blobs:\n"
    _code += "        left_blob, right_blob = get_top2_blobs(blobs)\n"
    _code += "        if(left_blob == None or right_blob == None):\n"
    _code += "            print(\"Out Of Range\")\n"
    _code += "            lcd.display(img, oft=(8,8))\n"
    _code += "            continue\n"
    _code += "        else:\n"
    _code += "            print(\"left blob\")\n"
    _code += "            print(left_blob)\n"
    _code += "            print(\"right blob\")\n"
    _code += "            print(right_blob)\n"

    _code += "            img.draw_circle(left_blob.cx(), left_blob.cy(), 3, thickness=2)\n"
    _code += "            img.draw_circle(right_blob.cx(), right_blob.cy(), 3, thickness=2)\n"
    _code += "            img.draw_line(left_blob.cx(), left_blob.cy(), right_blob.cx(), right_blob.cy(), thickness=2)\n"

    _code += "            direct_ratio = get_direction(left_blob, right_blob)\n"
    _code += "            img.draw_string(10, 33, \"%.2f\"%direct_ratio, mono_space=False)\n"

    _code += "            rect_color = (0,0,255)\n"
    _code += "            arrow_color = (255,255,255)\n"

    _code += "            if float(direct_ratio) < -0.1:\n"
    _code += "                img.draw_string(10, 10, \"Turn Left\", scale=2, mono_space=False)\n"
    _code += "                img.draw_rectangle(174,10,40,40,color=rect_color,fill=True)\n"
    _code += "                img.draw_arrow(207, 30,180, 30, color=arrow_color, thickness=3)\n"
    _code += "            elif float(direct_ratio) > 0.1:\n"
    _code += "                img.draw_string(10, 10, \"Turn Right\", scale=2, mono_space=False)\n"
    _code += "                img.draw_rectangle(174,10,40,40,color=rect_color,fill=True)\n"
    _code += "                img.draw_arrow(180, 30, 207, 30, color=arrow_color, thickness=3)\n"
    _code += "            elif int(direct_ratio) == 0:\n"
    _code += "                img.draw_string(10, 10, \"Go Straight\", scale=2, mono_space=False)\n"
    _code += "                img.draw_rectangle(174,10,40,40,color=rect_color,fill=True)\n"
    _code += "                img.draw_arrow(194, 40, 194, 20, color=arrow_color, thickness=3)\n"
    _code += "                # 將條件積木中放置的代碼放在此處...\n"
    return _code;
}

Blockly.Blocks['ai_vision_sgd'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_SIF_G);
        this.appendDummyInput()
            .appendField(Blockly.Msg.VISION_SIF_GF);
        this.setOutput(true, null);
        this.setColour("#f2a247");
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python.ai_vision_sgd = function(block) {
    var _code = "direct_ratio\n"
    return _code;
}

*/

/*
     _    ___   ____            _                 
    / \  |_ _| / ___| _   _ ___| |_ ___ _ __ ___  
   / _ \  | |  \___ \| | | / __| __/ _ \ '_ ` _ \ 
  / ___ \ | |   ___) | |_| \__ \ ||  __/ | | | | |
 /_/   \_\___| |____/ \__, |___/\__\___|_| |_| |_|
                      |___/                       
*/


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

Blockly.Python.ai_system_restart = function (block) {
  Blockly.Python.definitions_.import_machine = "import machine";
  var _code = "machine.reset()\n";
  return _code;
};

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

Blockly.Python.ai_system_gc = function (block) {
  Blockly.Python.definitions_.import_gc = "import gc";
  Blockly.Python.addSetup("ai_system_gc", "gc.enable()");
  var _code = "gc.collect()\n";
  return _code;
};

Blockly.Blocks['ai_system_run'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.ai_system_run_python_code);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.ai_system_run_python_code_file_path);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#d42b03");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_system_run = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _code = "exec(open(" + _path + ").read())\n";

  return _code;
};

Blockly.Blocks['ai_system_create'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_CREATE);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_CREATE_F);
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#1e3283");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_system_create = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _code = "def _CREATE_TEXT_FILE(_path):\n";
  _code += "    f = open(_path, 'w')\n";
  _code += "    f.close()\n";
  Blockly.Python.addFunction("_CREATE_TEXT_FILE", _code);
  _code = "_CREATE_TEXT_FILE(" + _path + ")\n";
  return _code;
};

Blockly.Blocks['ai_system_write'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_F);
    this.appendValueInput("WPATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_W);
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE_S).appendField(new Blockly.FieldDropdown([[Blockly.Msg.SYSTEM_WRITE_S_N, "newline"], [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"], [Blockly.Msg.SYSTEM_WRITE_S_S, "space"], [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]]), "separator");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#1e3283");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_system_write = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _wpath = Blockly.Python.valueToCode(block, 'WPATH', Blockly.Python.ORDER_ATOMIC);

  var _separator = block.getFieldValue('separator');

  var _code = "def _CREATE_TEXT_FILE_WITH_CONTENT(_path, _data, _sep):\n";
  _code += "    f = open(_path, 'a')\n";
  _code += "    f.write(_data + _sep)\n";
  _code += "    f.close()\n";
  Blockly.Python.addFunction("_CREATE_TEXT_FILE_WITH_CONTENT", _code);
  _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", '\\r\\n')";

  if (_separator == "newline") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", '\\r\\n')";
  } else if (_separator == "comma") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ',')";
  } else if (_separator == "space") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ' ')";
  } else if (_separator == "semicolon") {
    _code = "_CREATE_TEXT_FILE_WITH_CONTENT(" + _path + ", " + _wpath + ", ';')";
  }

  return _code;
};

Blockly.Blocks['ai_system_input'] = {
  init: function init() {
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_INPUT);
    this.appendValueInput("PATH").setCheck(null).appendField(Blockly.Msg.SYSTEM_WRITE_F);
    this.appendDummyInput().appendField(Blockly.Msg.SYSTEM_WRITE_S).appendField(new Blockly.FieldDropdown([[Blockly.Msg.SYSTEM_WRITE_S_N, "newline"], [Blockly.Msg.SYSTEM_WRITE_S_C, "comma"], [Blockly.Msg.SYSTEM_WRITE_S_S, "space"], [Blockly.Msg.SYSTEM_WRITE_S_SE, "semicolon"]]), "separator");
    this.setInputsInline(false);
    this.setPreviousStatement(true, null);
    this.setNextStatement(true, null);
    this.setColour("#1e3283");
    this.setTooltip("");
    this.setHelpUrl("");
  }
};

Blockly.Python.ai_system_input = function (block) {
  var _path = Blockly.Python.valueToCode(block, 'PATH', Blockly.Python.ORDER_ATOMIC);

  var _separator = block.getFieldValue('separator');

  var _code = "def _GET_LIST_FROM_FILE(_path, _sep):\n";
  _code += "    f = open(_path, 'r')\n";
  _code += "    result = f.read().split(_sep)\n";
  _code += "    f.close()\n";
  _code += "    return result\n";
  Blockly.Python.addFunction("_GET_LIST_FROM_FILE", _code);
  _code = "_GET_LIST_FROM_FILE(" + _path + ", '\\r\\n')";

  if (_separator == "newline") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", '\\r\\n')";
  } else if (_separator == "comma") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ',')";
  } else if (_separator == "space") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ' ')";
  } else if (_separator == "semicolon") {
    _code = "_GET_LIST_FROM_FILE(" + _path + ", ';')";
  }

  return _code;
};
/*


Blockly.Blocks['ai_serialport_print'] = {
    init: function() {
        this.jsonInit({
            message0: Blockly.Msg.SERIALPORT_PRINT_TITLE,
            args0: [{
                type: "input_value",
                name: "TEXT"
            }],
            previousStatement: null,
            nextStatement: null,
            colour: 65,
            tooltip: Blockly.Msg.TEXT_PRINT_TOOLTIP,
            helpUrl: Blockly.Msg.TEXT_PRINT_HELPURL
        })
    }
};

Blockly.Python.ai_serialport_print = function(block) {
    return "print(" + (Blockly.Python.valueToCode(block, "TEXT", Blockly.Python.ORDER_NONE) || "''") + ")\n";
}

Blockly.Blocks['ai_serialport_printall'] = {
    init: function() {
        this.appendDummyInput()
            .appendField(Blockly.Msg.SERIALPORT_PRINT_TITLE);
        this.appendDummyInput()
            .appendField(Blockly.Msg.SERIALPORT_SPACER)
            .appendField(new Blockly.FieldCheckbox("TRUE"), "spacer");
        this.appendDummyInput()
            .appendField(Blockly.Msg.SERIALPORT_TERMINATOR)
            .appendField(new Blockly.FieldCheckbox("TRUE"), "terminator");
        this.appendValueInput("data1")
            .setCheck("String")
            .appendField(Blockly.Msg.SERIALPORT_DATA + "1");
        this.appendValueInput("data2")
            .setCheck(null)
            .appendField(Blockly.Msg.SERIALPORT_DATA + "2");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(65);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Python.ai_serialport_printall = function(block) {
    var spacer = block.getFieldValue('spacer') == 'TRUE' ? "True" : "False";
    var terminator = block.getFieldValue('terminator') == 'TRUE' ? "True" : "False";;
    var data1 = Blockly.Python.valueToCode(block, 'data1', Blockly.Python.ORDER_ATOMIC);
    var data2 = Blockly.Python.valueToCode(block, 'data2', Blockly.Python.ORDER_ATOMIC);
    var _code = "print(" + data1 + ", " + data2 + ", sep='" + spacer + "', end='" + terminator + "') \n"
    return _code;
}

*/