import * as Blockly from 'blockly';
import { pythonGenerator } from 'blockly/python';

Blockly.Python = pythonGenerator || { Msg: Object.create(null) };

const wifiColor = '#7e3cca';
Blockly.Blocks['wifi_connect'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("WIFI连接")
            .appendField(new Blockly.FieldTextInput("wifi_name"), "wifi_name")
            .appendField("密码")
            .appendField(new Blockly.FieldTextInput("wifi_password"), "wifi_password");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(wifiColor);
        this.setTooltip("WiFi连接");
    }
}
Blockly.Python['wifi_connect'] = function (block) {
    var wifi_name = block.getFieldValue('wifi_name');
    var wifi_password = block.getFieldValue('wifi_password');
    var code = `wifi.connect("${wifi_name}", "${wifi_password}")`;
    return code;
};

Blockly.Blocks['wifi_disconnect'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("WIFI断开连接");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(wifiColor);
        this.setTooltip("WiFi断开连接");
    }
}
Blockly.Python['wifi_disconnect'] = function (block) {
    var code = `wifi.disconnect()`;
    return code;
};

Blockly.Blocks['wifi_is_connected'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("WIFI是否连接");
        this.setOutput(true, null);
        this.setColour(wifiColor);
        this.setTooltip("WIFI是否连接");
    }
}
Blockly.Python['wifi_is_connected'] = function (block) {
    var code = `wifi.status()`;
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['wifi_get_ip'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("获取WIFI IP");
        this.setOutput(true, null);
        this.setColour(wifiColor);
        this.setTooltip("获取WIFI IP");
    }
}
Blockly.Python['wifi_get_ip'] = function (block) {
    var code = `wifi.get_ip()`;
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['network_time'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("获取网络时间");
        this.setNextStatement(true, null);
        this.setPreviousStatement(true, null);
        this.setColour(wifiColor);
        this.setTooltip("获取网络时间");
    }
}

const networkColor = '#3062c1';
Blockly.Blocks['set_network_weather'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.set_weather_city)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.beijing, "101010100"],
                [Blockly.Msg.shanghai, "101020100"],
                [Blockly.Msg.guangzhou, "101280101"],
                [Blockly.Msg.shenzhen, "101280601"],
                [Blockly.Msg.HongKong, "101320101"],
            ]), "get_city")
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.set_weather_city);
    }
}
Blockly.Python['set_network_weather'] = function (block) {
    var city = block.getFieldValue('get_city');
    Blockly.Python.definitions_["import_requests"] = `import requests`;
    Blockly.Python.definitions_["hefengGetWeather"] = `def hefengGetWeather(city,lang):
  getWeatherUrl = f"https://devapi.qweather.com/v7/weather/now?location={city}&key=d8d1d01bac3246ee8c34640681c1c9b6&lang={lang}"
  weatherResult = ""
  try:
    responseResult = requests.get(getWeatherUrl)
    if responseResult.status_code == 200:
      weatherResult = responseResult.json()
  except:
    pass
  return weatherResult
`
    let lang = localStorage.getItem("lang") == 2 ? "zh-hans" : localStorage.getItem("lang") == 0 ? "en" : "zh-hant"
    var code = `getWeatherResult = hefengGetWeather("${city}","${lang}")`;
    return code;
};

Blockly.Blocks['get_network_weather'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.ESP32_ENV_GET_TEXT)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.weather_resulet, "result"],
                [Blockly.Msg.image_process_temperature, "temp"],
                [Blockly.Msg.weather_condition, "text"],
                [Blockly.Msg.windDir, "windDir"],
                [Blockly.Msg.windScale, "windScale"],
                [Blockly.Msg.windSpeed, "windSpeed"],
                [Blockly.Msg.image_process_humidity, "humidity"],
            ]), "get_weather")
        this.setOutput(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.get_weather_city);
    }
}
Blockly.Python['get_network_weather'] = function (block) {
    var weather = block.getFieldValue('get_weather');
    var code = "";
    if (weather == "result") {
        code = `getWeatherResult`
    } else {
        code = `getWeatherResult["now"]["${weather}"]`
    }
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['esp32_main_controller_ifttt_send_data'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_send_title);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_send_webhook)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "ifttt_api_key");
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_send_eventname)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "ifttt_event");
        this.appendValueInput("ifttt_data_1")
            .setCheck(null)
            .appendField(Blockly.Msg.iotservice_ifttt_send_1);
        this.appendValueInput("ifttt_data_2")
            .setCheck(null)
            .appendField(Blockly.Msg.iotservice_ifttt_send_2);
        this.appendValueInput("ifttt_data_3")
            .setCheck(null)
            .appendField(Blockly.Msg.iotservice_ifttt_send_3);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Send_Data_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_main_controller_ifttt_send_data'] = function (block) {
    var text_ifttt_api_key = block.getFieldValue('ifttt_api_key');
    var text_ifttt_event = block.getFieldValue('ifttt_event');
    var value_ifttt_data_1 = Blockly.Python.valueToCode(block, 'ifttt_data_1', Blockly.Python.ORDER_ATOMIC);
    var value_ifttt_data_2 = Blockly.Python.valueToCode(block, 'ifttt_data_2', Blockly.Python.ORDER_ATOMIC);
    var value_ifttt_data_3 = Blockly.Python.valueToCode(block, 'ifttt_data_3', Blockly.Python.ORDER_ATOMIC);
    // TODO: Assemble Python into code variable.

    Blockly.Python.definitions_['v831_import_requests'] = `import requests`
    Blockly.Python.definitions_['v831_import_json'] = `import json`;

    var code = '' +
        '_IFTTT_POST_API_KEY = "' + text_ifttt_api_key + '"\n' +
        '_IFTTT_POST_EVENT_NAME = "' + text_ifttt_event + '"\n' +
        '_IFTTT_POST_ENDPOINT = "http://maker.ifttt.com/trigger/"+ _IFTTT_POST_EVENT_NAME + "/with/key/" + _IFTTT_POST_API_KEY\n' +
        '_IFTTT_POST_DATA = \'{"value1":"\'+ str(' + value_ifttt_data_1 + ') +\'","value2":"\'+ str(' + value_ifttt_data_2 + ') +\'","value3":"\'+ str(' + value_ifttt_data_3 + ') +\'"}\'\n' +
        '_IFTTT_POST_REQUEST = requests.post(_IFTTT_POST_ENDPOINT, data = _IFTTT_POST_DATA , headers = { "Content-type": "application/json" }, timeout=60)\n' +
        '\n';
    return code;
};



Blockly.Blocks['esp32_main_controller_ifttt_touched'] = {
    init: function () {
        // this.appendDummyInput()
        //     .appendField(new Blockly.FieldImage("blockly/media/ifttt_webhook.png", 110, 60, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_trigger_title);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_trigger_webhook)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_API_KEY"), "key");
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_ifttt_trigger_eventname)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_EVENT_NAME"), "timename");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Esp32_Main_Controller_Ifttt_Touched_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['esp32_main_controller_ifttt_touched'] = function (block) {
    var text_ifttt_api_key = block.getFieldValue('key');
    var text_timename = block.getFieldValue('timename');
    Blockly.Python.definitions_['v831_import_requests'] = `import requests`
    Blockly.Python.definitions_['v831_import_json'] = `import json`;
    var code = '_IFTTT_TRIGGER_EVENT_NAME = "' + text_timename + '"\n'
    code += '_IFTTT_TRIGGER_API_KEY = "' + text_ifttt_api_key + '"\n'
    code += '_IFTTT_TRIGGER_ENDPOINT = "https://maker.ifttt.com/trigger/" + _IFTTT_TRIGGER_EVENT_NAME + "/with/key/" + _IFTTT_TRIGGER_API_KEY\n'
    var code = '_IFTTT_GET_REQUEST = requests.get(_IFTTT_TRIGGER_ENDPOINT, timeout=60)\n'
    return code;
};
Blockly.Blocks['iot_service_thingspeak'] = {
    init: function () {
        // this.appendDummyInput()
        //     .appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_send_title);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_send_api)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_WRITE_API_KEY"), "t_api");
        this.itemCount_ = 1;
        this.updateShape_();
        this.setMutator(new Blockly.icons.MutatorIcon(['iot_service_thingspeak_create_with_item'], this));
        this.setColour(networkColor);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_TOOLTIP);
        this.setHelpUrl("");
    },
    mutationToDom: function () {
        var container = document.createElement('mutation');
        container.setAttribute('items', this.itemCount_);
        return container;
    },
    domToMutation: function (xmlElement) {
        this.itemCount_ = parseInt(xmlElement.getAttribute('items'), 10);
        this.updateShape_();
    },
    decompose: function (workspace) {
        var containerBlock = workspace.newBlock('iot_service_thingspeak_create_with_container');
        containerBlock.initSvg();
        var connection = containerBlock.getInput('STACK').connection;
        for (var i = 0; i < this.itemCount_; i++) {
            var itemBlock = workspace.newBlock('iot_service_thingspeak_create_with_item');
            itemBlock.initSvg();
            connection.connect(itemBlock.previousConnection);
            connection = itemBlock.nextConnection;
        }
        return containerBlock;
    },
    compose: function (containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        // Count number of inputs.
        var connections = [];
        while (itemBlock) {
            connections.push(itemBlock.valueConnection_);
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
        // Disconnect any children that don't belong.
        for (var i = 0; i < this.itemCount_; i++) {
            var connection = this.getInput('ADD' + i).connection.targetConnection;
            if (connection && connections.indexOf(connection) == -1) {
                connection.disconnect();
            }
        }
        this.itemCount_ = connections.length;
        this.updateShape_();
        // Reconnect any child blocks.
        for (var i = 0; i < this.itemCount_; i++) {
            Blockly.icons.MutatorIcon.reconnect(connections[i], this, 'ADD' + i);
        }
    },
    saveConnections: function (containerBlock) {
        var itemBlock = containerBlock.getInputTargetBlock('STACK');
        var i = 0;
        while (itemBlock) {
            var input = this.getInput('ADD' + i);
            itemBlock.valueConnection_ = input && input.connection.targetConnection;
            i++;
            itemBlock = itemBlock.nextConnection &&
                itemBlock.nextConnection.targetBlock();
        }
    },
    updateShape_: function () {
        for (var i = 0; i < this.itemCount_; i++) {
            if (!this.getInput('ADD' + i)) {
                var input = this.appendValueInput('ADD' + i);
                input.appendField("Field " + (i + 1) + ":");
                //input.appendField(new Blockly.FieldLabelSerializable("field" + (i + 1)), 'FIELD' + i);
                // input.appendField(new Blockly.FieldTextInput("field" + (i + 1)), 'FIELD' + i)
            }
        }
        while (this.getInput('ADD' + i)) {
            this.removeInput('ADD' + i);
            i++;
        }
    },
};

Blockly.Blocks['iot_service_thingspeak_create_with_container'] = {
    init: function () {
        this.setColour(networkColor);
        this.appendDummyInput()
            .appendField("Items");
        this.appendStatementInput('STACK');
        this.setTooltip('');
        this.contextMenu = false;
    }
};

Blockly.Blocks['iot_service_thingspeak_create_with_item'] = {
    init: function () {
        this.setColour(networkColor);
        this.appendDummyInput()
            .appendField("Field");
        this.setPreviousStatement(true);
        this.setNextStatement(true);
        this.setTooltip('');
        this.contextMenu = false;
    }
};

Blockly.Python['iot_service_thingspeak'] = function (block) {
    var first_input = Blockly.Python.valueToCode(block, 'first_input', Blockly.Python.ORDER_ATOMIC);
    var api = block.getFieldValue('t_api');

    // Blockly.Python.addVariable('_THINGSPEAK_REQUEST', '', true);
    Blockly.Python.definitions_['v831_import_requests'] = `import requests`
    Blockly.Python.definitions_['v831_import_json'] = `import json`;


    // var key = Blockly.Arduino.valueToCode(block, 'KEY', Blockly.Arduino.ORDER_ATOMIC).replace(/\"/g, '') || "";

    var item_field = '',
        item_value = '';
    var thingspeak_url = "http://api.thingspeak.com/update?api_key=" + api;
    for (var n = 0; n < this.itemCount_; n++) {
        item_field = "field" + (n + 1);
        item_value = Blockly.Python.valueToCode(this, 'ADD' + n,
            Blockly.Python.ORDER_NONE) || '';
        thingspeak_url += '&' + item_field + '=\"+str(' + item_value + ')+\"';
    }
    var code = '' +
        '_THINGSPEAK_ENDPOINT = "' + thingspeak_url + '"\n' +
        '_THINGSPEAK_REQUEST = requests.get(_THINGSPEAK_ENDPOINT,timeout=60)\n' +
        '';

    return code;
};

Blockly.Blocks['iot_service_thingspeak_read'] = {
    init: function () {
        // this.appendDummyInput()
        //     .appendField(new Blockly.FieldImage("blockly/media/thingspeak.png", 170, 45, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_query_title);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_query_api)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_READ_API_KEY"), "api_key");
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_channel_id)
            .appendField(new Blockly.FieldTextInput("ENTER_YOUR_CHANNEL_ID"), "id");
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_TOOLTIP);
        this.setHelpUrl("");
    }
};


Blockly.Python['iot_service_thingspeak_read'] = function (block) {
    var text_api_key = block.getFieldValue('api_key');
    var text_id = block.getFieldValue('id');
    Blockly.Python.definitions_['v831_import_requests'] = `import requests`
    Blockly.Python.definitions_['v831_import_json'] = `import json`;

    Blockly.Python.addVariable('_THINGSPEAK_READ_REQUEST', '', true);
    // TODO: Assemble Python into code variable.
    var code = '_THINGSPEAK_READ_REQUEST = requests.get("https://api.thingspeak.com/channels/" + "' + text_id + '" + "/feeds.json?api_key=" + "' + text_api_key + '",timeout=60)\n';
    return code;
};


Blockly.Blocks['iot_service_thingspeak_read_total'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_read_total);
        this.setInputsInline(false);
        this.setOutput(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Total_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['iot_service_thingspeak_read_total'] = function (block) {
    // TODO: Assemble Python into code variable.
    var code = '_THINGSPEAK_READ_REQUEST.json()[\'channel\'][\'last_entry_id\']';
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_NONE];
};


Blockly.Blocks['iot_service_thingspeak_read_specific'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeak_get_title);
        this.appendValueInput("entry")
            .setCheck(null);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeaK_get_field);
        this.appendValueInput("field")
            .setCheck(null);
        this.appendDummyInput()
            .appendField(Blockly.Msg.iotservice_thingspeaK_get_value);
        this.setInputsInline(true);
        this.setOutput(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Iot_Service_Thingspeak_Read_Specific_TOOLTIP);
        this.setHelpUrl("");
    }
};

Blockly.Python['iot_service_thingspeak_read_specific'] = function (block) {
    var value_entry = Blockly.Python.valueToCode(block, 'entry', Blockly.Python.ORDER_ATOMIC);
    var value_field = Blockly.Python.valueToCode(block, 'field', Blockly.Python.ORDER_ATOMIC);
    // TODO: Assemble Python into code variable.
    var code = '_THINGSPEAK_READ_REQUEST.json()[\'feeds\'][' + value_entry + '][\'field' + value_field + '\']';
    // TODO: Change ORDER_NONE to the correct strength.
    return [code, Blockly.Python.ORDER_NONE];
};


// 发送邮件

Blockly.Blocks['cocopi_email_send'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.send_email_title);
        this.appendValueInput("email")
            .setCheck(null)
            .appendField(Blockly.Msg.send_email_to);
        this.appendValueInput("email_content")
            .setCheck(null)
            .appendField(Blockly.Msg.send_email_content);
        this.setOutput(true);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.send_email_title_title);
        this.setHelpUrl("");
    }
};

Blockly.Python['cocopi_email_send'] = function (block) {
    var Email = Blockly.Python.valueToCode(block, 'email', Blockly.Python.ORDER_ATOMIC);
    var EmailContent = Blockly.Python.valueToCode(block, 'email_content', Blockly.Python.ORDER_ATOMIC);

    Blockly.Python.definitions_['import_requests'] = `import requests`
    Blockly.Python.definitions_['import_json'] = `import json`;
    // TODO: Assemble Python into code variable.
    Blockly.Python.definitions_['send_email'] = `def send_email(email,content):
    params = {
        "email": email,
        "content": content,
        "subject":"训练平台",
        "content_type":'plain'
    }
    emailURL = "https://traininguser-api.cocorobo.cn/sendEmail"
    try:
        r = requests.post(emailURL,json=params)
        print(json.loads(r.text))
        if json.loads(r.text)["FunctionResponse"] == "发送成功":
            return True
        else:
            return False
    except Exception as e:
        print(e)
        return False
    `
    var code = `send_email(${Email},${EmailContent})`;
    return [code, Blockly.Python.ORDER_NONE];
};


// socket 
const socketColor = '#5C8EFF';
Blockly.Blocks['socket_TCP_server_init'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("TCP服务端初始化");
        this.setNextStatement(true, null);
        this.setColour(socketColor);
        this.setTooltip("TCP服务端初始化");
        this.setPreviousStatement(true, null);
    }
};
Blockly.Python['socket_TCP_server_init'] = function (block) {
    Blockly.Python.definitions_['import_socket'] = `import socket`;
    Blockly.Python.definitions_['socket_TCP_server_init'] = `def socket_TCP_server_init():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('', 8888))
    s.listen(5)
    return s
    `;
    var code = `socket_TCP_server_init()`;
    return code;
};

Blockly.Blocks['socket_TCP_server_send'] = {
    init: function () {
        this.appendValueInput("data").setCheck(null).appendField("服务端发送数据");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(socketColor);
        this.setTooltip("服务端发送数据");
    }
}
Blockly.Python['socket_TCP_server_send'] = function (block) {
    // var value_data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['socket_TCP_server_send'] = `def socket_TCP_server_send(s,data):
    s.send(data.encode())
    `;
    let code = `socket_TCP_server_send(s)`;
    return code;
}
Blockly.Blocks['socket_TCP_server_receive'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("服务端接收数据");
        this.setOutput(true, null);
        this.setColour(socketColor);
        this.setTooltip("服务端接收数据");
    }
}
Blockly.Python['socket_TCP_server_receive'] = function (block) {
    Blockly.Python.definitions_['socket_TCP_server_receive'] = `def socket_TCP_server_receive(s):
    data = s.recv(1024)
    return data.decode()
    `;
    var code = `socket_TCP_server_receive(s)`;
    return code;
}

Blockly.Blocks['socket_TCP_client_init'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("客户端初始化");
        this.setPreviousStatement(true, null);
        this.setColour(socketColor);
        this.setTooltip("客户端初始化");
    }
}
Blockly.Python['socket_TCP_client_init'] = function (block) {
    Blockly.Python.definitions_['import_socket'] = `import socket`;
    Blockly.Python.definitions_['socket_TCP_client_init'] = `def socket_TCP_client_init():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('192.168.1.100', 888))`
    let code = `socket_TCP_client_init()`;
    return code
}

Blockly.Blocks['socket_TCP_client_send'] = {
    init: function () {
        this.appendValueInput("data").setCheck(null).appendField("客户端发送数据");
        this.setNextStatement(true, null);
        this.setPreviousStatement(true, null);
        this.setColour(socketColor);
        this.setTooltip("客户端发送数据");
    }
}
Blockly.Python['socket_TCP_client_send'] = function (block) {
    // var value_data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['socket_TCP_client_send'] = `def socket_TCP_client_send(s,data):
    s.send(data.encode())
    `;
    let code = `socket_TCP_client_send(s)`;
    return code;
}

Blockly.Blocks['socket_TCP_client_receive'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("客户端接收数据");
        this.setOutput(true, null);
        this.setColour(socketColor);
        this.setTooltip("客户端接收数据");
    }
}
Blockly.Python['socket_TCP_client_receive'] = function (block) {
    Blockly.Python.definitions_['socket_TCP_client_receive'] = `def socket_TCP_client_receive(s):
    data = s.recv(1024)
    return data.decode()
    `;
    var code = `socket_TCP_client_receive(s)`;
    return code;
}

Blockly.Blocks['socket_TCP_client_close'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("客户端关闭连接");
        this.setPreviousStatement(true, null);
        this.setColour(socketColor);
        this.setTooltip("客户端关闭连接");
    }
}
Blockly.Python['socket_TCP_client_close'] = function (block) {
    Blockly.Python.definitions_['socket_TCP_client_close'] = `def socket_TCP_client_close(s):
    s.close()
    `;
    var code = `socket_TCP_client_close(s)`;
    return code;
}


// MQTT
const mqttColor = '#e8795b';
Blockly.Blocks['MQTT_connected'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("MQTT连接");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(mqttColor);
        this.setTooltip("MQTT连接");
    }
};
Blockly.Python['MQTT_connected'] = function (block) {
    Blockly.Python.definitions_['import_paho'] = `import paho.mqtt.client as mqtt`;
    Blockly.Python.definitions_['mqtt_connect'] = `def mqtt_connect():
    client = mqtt.Client()
    client.connect("mqtt.eclipse.org", 1883, 60)
    return client   
`;
    var code = `mqtt_connect()`;
    return code;
};

Blockly.Blocks['MQTT_is_connected'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("MQTT是否连接");
        this.setOutput(true, null);
        this.setColour(mqttColor);
        this.setTooltip("MQTT是否连接");
        this.setHelpUrl("");
    }
}
Blockly.Python['MQTT_is_connected'] = function (block) {
    Blockly.Python.definitions_['MQTT_is_connected'] = `def MQTT_is_connected(client):
    return client.is_connected()
`;
    var code = `MQTT_is_connected(client)`;
    return [code, Blockly.Python.ORDER_NONE];
};

Blockly.Blocks['mqtt_subscribe'] = {
    init: function () {
        this.appendValueInput("content")
            .setCheck(null).appendField("发送");
        this.appendValueInput("topic")
            .setCheck(null).appendField("内容到主题");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(mqttColor);
        this.setTooltip("MQTT订阅主题");
        this.setInputsInline(true);
    }
}
Blockly.Python['mqtt_subscribe'] = function (block) {
    var topic = Blockly.Python.valueToCode(block, 'topic', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['mqtt_subscribe'] = `def mqtt_subscribe(client, topic):
    client.subscribe(topic)
`;
    var code = `mqtt_subscribe(client, ${topic})`;
    return code;
};

Blockly.Blocks['mqtt_received'] = { 
    init: function () { 
        this.appendValueInput("topic").setCheck(null).appendField("当从主题")
        this.appendDummyInput().appendField("收到消息时");
        this.appendStatementInput("exec")
            .setCheck(null)
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_do);
        this.setColour(mqttColor);
        this.setTooltip("当从主题收到消息时");
        this.setHelpUrl("");
        this.setNextStatement(true, null);
        this.setPreviousStatement(true, null);
    }
};
Blockly.Python['mqtt_received'] = function (block) {
    var path = block.getFieldValue('path');
    var statements_exec = Blockly.Python.statementToCode(block, 'exec');
    Blockly.Python.definitions_['mqtt_on_message'] = `def on_message(client, userdata, msg):
    topic = msg.topic
    message = msg.payload.decode()
    print("Received message: " + message + " from topic: " + topic)
`;
    let code = ``;
    return code;
}

Blockly.Blocks['mqtt_accept_data'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("接收MQTT数据");
        this.setOutput(true, null);
        this.setColour(mqttColor);
        this.setTooltip("接收MQTT数据");
    }
}
Blockly.Python['mqtt_accept_data'] = function (block) {
    Blockly.Python.definitions_['mqtt_accept_data'] = `def mqtt_accept_data(client
):
    client.loop_start()
    return client`;
    var code = `mqtt_accept_data(client)`;
    return [code, Blockly.Python.ORDER_NONE];
};

// WebSocket
const websocketColor = '#5C81A6';
Blockly.Blocks['websocket_server_init'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("websocket服务端初始化");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket服务端初始化");
    }
};
Blockly.Python['websocket_server_init'] = function (block) {
    Blockly.Python.definitions_['import_websocket'] = `import websocket`;
    Blockly.Python.definitions_['websocket_server_init'] = `def websocket_server_init():
    ws = websocket.WebSocketServer('192.168.1.100', 8080)
    return ws`;
    var code = `websocket_server_init()`;
    return code;

}

Blockly.Blocks['websocket_server_receive'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("websocket服务端接收数据");
        this.setOutput(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket服务端接收数据");
    }
}
Blockly.Python['websocket_server_receive'] = function (block) {
    Blockly.Python.definitions_['websocket_server_receive'] = `def websocket_server_receive(ws):
    data = ws.recv()
    return data`;
    var code = `websocket_server_receive(ws)`;
    return [code, Blockly.Python.ORDER_NONE];
}

Blockly.Blocks['websocket_server_send'] = {
    init: function () {
        this.appendValueInput("data").setCheck(null).appendField("websocket服务端发送数据");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket服务端发送数据");
    }
}
Blockly.Python['websocket_server_send'] = function (block) {
    var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['websocket_server_send'] = `def websocket_server_send(ws, data):
    ws.send(data)`;
    var code = `websocket_server_send(ws, ${data})`;
    return code;
}

Blockly.Blocks['websocket_client_init'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("websocket客户端初始化");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket客户端初始化");
    }
}
Blockly.Python['websocket_client_init'] = function (block) {
    Blockly.Python.definitions_['import_websocket'] = `import websocket`;
    Blockly.Python.definitions_['websocket_client_init'] = `def websocket_client_init():
    ws = websocket.WebSocket()
    ws.connect('ws://192.168.1.100:8080')
    return ws`;
    var code = `websocket_client_init()`;
    return code;
}

Blockly.Blocks['websocket_client_receive'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("websocket客户端接收数据");
        this.setOutput(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket客户端接收数据");
    }
}
Blockly.Python['websocket_client_receive'] = function (block) {
    Blockly.Python.definitions_['websocket_client_receive'] = `def websocket_client_receive(ws):
    data = ws.recv()
    return data`;
    var code = `websocket_client_receive(ws)`;
    return [code, Blockly.Python.ORDER_NONE];
}

Blockly.Blocks['websocket_client_send'] = {
    init: function () {
        this.appendValueInput("data").setCheck(null).appendField("websocket客户端发送数据");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket客户端发送数据");
    }
}
Blockly.Python['websocket_client_send'] = function (block) {
    var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['websocket_client_send'] = `def websocket_client_send(ws, data):
    ws.send(data)`;
    var code = `websocket_client_send(ws, ${data})`;
    return code;
}

Blockly.Blocks['websocket_client_close'] = {
    init: function () {
        this.appendDummyInput()
            .appendField("websocket客户端关闭");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(websocketColor);
        this.setTooltip("websocket客户端关闭");
    }
}
Blockly.Python['websocket_client_close'] = function (block) {
    Blockly.Python.definitions_['websocket_client_close'] = `def websocket_client_close(ws):
    ws.close()`;
    var code = `websocket_client_close(ws)`;
    return code;
}

// Flask Web
Blockly.Blocks['websocket_server_set_request'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_title);
        this.appendDummyInput()
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_path)
            .appendField(new Blockly.FieldTextInput("/"), "path")
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_being_requested);
        this.appendDummyInput()
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_property)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.wifi_web_http_server_route_setting_get, "get"],
                [Blockly.Msg.wifi_web_http_server_route_setting_post, "post"]
            ]), "response_type");
        this.appendStatementInput("exec")
            .setCheck(null)
            .appendField(Blockly.Msg.wifi_web_http_server_route_setting_do);
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        // this.setTooltip("");
        this.setHelpUrl("");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('response_type');
            var TOOLTIPS = {
                'get': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_get),
                'post': Blockly.Msg.Esp32_Network_Http_Server_Route_TOOLTIP.replace('%1', Blockly.Msg.wifi_web_http_server_route_setting_post)
            };
            return TOOLTIPS[mode];
        });
    }
}
Blockly.Python['websocket_server_set_request'] = function () {
    var dropdown_response_type = block.getFieldValue('response_type');
    var text_path = block.getFieldValue('path');
    var statements_exec = Blockly.Python.statementToCode(block, 'exec');
    var code = ``;
    return code;
}

Blockly.Blocks['network_http_get'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.internet_http_get_title);
        this.appendValueInput("http_get_url")
            .setCheck(null)
            .appendField(Blockly.Msg.internet_http_get_url);
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Esp32_Network_Http_Get_TOOLTIP);
        this.setHelpUrl("");
    }
}

Blockly.Python['network_http_get'] = function (block) {
    var url = Blockly.Python.valueToCode(block, 'http_get_url', Blockly.Python.ORDER_ATOMIC);
    Blockly.Python.definitions_['v831_import_requests'] = `import requests`
    Blockly.Python.definitions_['v831_import_json'] = `import json`;
    Blockly.Python.definitions_['v831_import_SEND_HTTP'] = `_SEND_HTTP_GET_ENDPOINT = ${url}`;
    // TODO: Assemble Python into code variable.

    var code = '_SEND_HTTP_REQUEST = requests.get(_SEND_HTTP_GET_ENDPOINT)\n';
    return code;
};

Blockly.Blocks['network_http_post'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(new Blockly.FieldImage("blockly/media/http_header_post.png", 180, 50, { alt: "*", flipRtl: "FALSE" }));
        this.appendDummyInput()
            .appendField(Blockly.Msg.internet_http_post_title);
        this.appendValueInput("http_post_url")
            .setCheck(null)
            .appendField(Blockly.Msg.internet_http_post_url);
        this.appendValueInput("data")
            .setCheck(null)
            .appendField(Blockly.Msg.internet_http_post_json);
        this.setInputsInline(false);
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(networkColor);
        this.setTooltip(Blockly.Msg.Esp32_Network_Http_Post_TOOLTIP);
        this.setHelpUrl("");
    }
};


Blockly.Python['network_http_post'] = function (block) {
    var url = Blockly.Python.valueToCode(block, 'http_post_url', Blockly.Python.ORDER_ATOMIC);
    var data = Blockly.Python.valueToCode(block, 'data', Blockly.Python.ORDER_ATOMIC);

    Blockly.Python.addVariable('_SEND_HTTP_POST_ENDPOINT', '', true);
    Blockly.Python.addVariable('_SEND_HTTP_REQUEST', '', true);
    Blockly.Python.definitions_['831_import_requests'] = `import requests`
    Blockly.Python.definitions_['831_import_json'] = `import json`
    Blockly.Python.definitions_['import_urequests'] = '' +
        '_SEND_HTTP_POST_ENDPOINT = ' + url + '\n' +
        '';
    // TODO: Assemble Python into code variable.

    // var code = '' +
    //     '_SEND_HTTP_POST_DATA = \'' + data + '\'\n' +
    //     '_SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, data = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })\n' +
    //     '';
    var code = `_SEND_HTTP_POST_DATA = ${data}
_SEND_HTTP_REQUEST = requests.post(_SEND_HTTP_POST_ENDPOINT, json = _SEND_HTTP_POST_DATA , headers = { "Content-type": "application/json" })
`
    return code;
};

Blockly.Blocks['CocoRobo_get'] = {
    init: function () {
        this.appendDummyInput()
            .appendField(Blockly.Msg.internet_response_http_content_title)
            .appendField(new Blockly.FieldDropdown([
                [Blockly.Msg.internet_response_text, "text"],
                [Blockly.Msg.internet_response_content, "content"],
                [Blockly.Msg.internet_response_status, "state"],
                [Blockly.Msg.internet_response_json, "json"],
                [Blockly.Msg.internet_response_encode, "code"],
                [Blockly.Msg.internet_response_reason, "reason"]
            ]), "op");
        this.setOutput(true, null);
        this.setColour(networkColor);
        // this.setTooltip(Blockly.Msg.CocoRobo_get_TOOLTIP);
        this.setHelpUrl("");
        var thisBlock = this;
        this.setTooltip(function () {
            var mode = thisBlock.getFieldValue('op');
            var TOOLTIPS = {
                'text': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_text),
                'content': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_content),
                'state': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_status),
                'json': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_json),
                'code': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_encode),
                'reason': Blockly.Msg.CocoRobo_get_TOOLTIP.replace('%1', Blockly.Msg.internet_response_reason)
            };
            return TOOLTIPS[mode];
        });
    }
};

Blockly.Python['CocoRobo_get'] = function (block) {
    var op = block.getFieldValue('op');
    var code = '_SEND_HTTP_REQUEST.text';
    if (op == "text") {
        code = '_SEND_HTTP_REQUEST.text';
    } else if (op == "content") {
        code = '_SEND_HTTP_REQUEST.content';
    } else if (op == "state") {
        code = '_SEND_HTTP_REQUEST.status_code';
    } else if (op == "json") {
        code = '_SEND_HTTP_REQUEST.json()';
    } else if (op == "code") {
        code = '_SEND_HTTP_REQUEST.encoding';
    } else if (op == "reason") {
        code = '_SEND_HTTP_REQUEST.reason';
    }
    return [code, Blockly.Python.ORDER_CONDITIONAL];
};


export default Blockly;