'use strict';

goog.provide('Blockly.Python.wifiserver');
goog.require('Blockly.Python');

// Blockly.Python['wifiServer_setup'] = function (block) {
//   var wifi_webserver= "#include <ESP8266WebServer.h>";
//   Blockly.Python.addInclude("wifi_webserver",wifi_webserver);
//   var port= Blockly.Python.valueToCode(block, 'PORT', Blockly.Python.ORDER_ATOMIC) || 80;
//   var code="ESP8266WebServer server("+port+");"
//   Blockly.Python.addDeclaration("setupServer_"+port, code);
//   return "";
// };

// Blockly.Python['wifiserver_setRouter'] = function (block) {
//   var response= Blockly.Python.valueToCode(block, "VAR", Blockly.Python.ORDER_ATOMIC) || "";
//   var url= block.getFieldValue("URL") || "/";
//   var code= "server.on(\""+url+"\", []() {"+response+"});"
//   Blockly.Python.addSetup("setRouter_"+url, code);
//   return "";
// };

Blockly.Python['wifiServer_onNotFound'] = function(block) {
    var response = Blockly.Python.valueToCode(block, "VAR", Blockly.Python.ORDER_ATOMIC) || "";
    var code = "server.onNotFound(" + response + ");";
    Blockly.Python.addSetup("setRouter_urlNotFound", code);
    return "";
};

Blockly.Python['wifiServer_serverSend'] = function(block) {
    var http_code = Blockly.Python.valueToCode(block, "CODE", Blockly.Python.ORDER_ATOMIC) || "";
    var type = Blockly.Python.valueToCode(block, "TYPE", Blockly.Python.ORDER_ATOMIC) || "";
    var content = Blockly.Python.valueToCode(block, "CONTENT", Blockly.Python.ORDER_ATOMIC) || "";
    var code = "server.send(" + http_code + "," + type + "," + content + ");";
    return [code, Blockly.Python.ORDER_ATOMIC];
};

Blockly.Python['wifiServer_handleClient'] = function(block) {
    var code = "server.handleClient()\n";
    return code;
};

Blockly.Python['wifiServer_waitConnection'] = function(block) {
    var code = "";
    return "";
};


/***********************
 *     version 2       *
 ***********************/

Blockly.Python['wifiServer_setup'] = function(block) {
    var wifi_server = "#include <ESP8266WebServer.h>";
    Blockly.Python.addInclude("wifi_server", wifi_server);
    var json_include = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("json_include", json_include);
    var codes = "ESP8266WebServer server(80);"
    Blockly.Python.addDeclaration("SetupWiFiServer_80", codes);
    var code = "";
    return code;
};

Blockly.Python['wifiServer_setRouter'] = function(block) {
    var code = "";
    for (let i = 0; i < block.itemCount_; i++) {
        var item_url = block.getFieldValue("URL" + i) || "/" + i;
        var item_code = Blockly.Python.statementToCode(block, 'STATEMENT' + i);
        code += "server.on(\"" + item_url + "\",[]() {\n" + item_code + "\n" +
            "  server.send(200,\"text/plain\",\"200\")\n" +
            "})\n"
    }
    Blockly.Python.addSetup("setRouter", code);

    code = "  server.onNotFound([]() {\n" +
        "    server.send(404,\"text/plain\",\"404:Not found\")\n" +
        "  });";
    Blockly.Python.addSetup("setRouter_onNotFound", code);
    Blockly.Python.addSetup("ServerBegin", "server.begin()\n")
    return "server.handleClient()\n";
};

Blockly.Python['wifiServer_setRootPage'] = function(block) {
    var code = "";
    var item_code = Blockly.Python.statementToCode(block, 'STATEMENT0');
    code += "server.on(\"/\",[]() {\n" + item_code + "\n" +
        "  server.send(200,\"text/plain\",\"200\")\n" +
        "})\n"
    Blockly.Python.addSetup("setRootPage", code);

    code = "  server.onNotFound([]() {\n" +
        "    server.send(404,\"text/plain\",\"404:Not found\")\n" +
        "  });";
    Blockly.Python.addSetup("setRouter_onNotFound", code);

    Blockly.Python.addSetup("ServerBegin", "server.begin()\n")
    return "server.handleClient()\n";
};

Blockly.Python['wifiServer_Send'] = function(block) {
    var json_include = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("json_include", json_include);
    // var precode = "char JSONServerMsgBuffer[240]\n";
    // Blockly.Python.addDeclaration("jsontool_prettyPrint", precode);
    var VarName = block.getFieldValue('VAR') || "json";
    var code = "StaticJsonBuffer<800> Serverbuffer_" + VarName + "\n" +
        "JsonObject& " + VarName + "_json_ = Serverbuffer_" + VarName + ".createObject()\n" +
        "JsonArray& data_json_S = " + VarName + "_json_.createNestedArray(\"data\")\n" +
        // "JsonArray& data_type_S = " + VarName + "_json_.createNestedArray(\"type\")\n"+
        "";
    var size = block.itemCount_;
    var item_value = '';
    for (var n = 0; n < block.itemCount_; n++) {
        item_value = Blockly.Python.valueToCode(block, 'ADD' + n,
            Blockly.Python.ORDER_NONE) || '';
        code += 'data_json_S.add(' + item_value + ")\n";
        // if (block.childBlocks_[n].type == "text") {
        //     code += "data_type_S.add(0)\n";
        // } else if (block.childBlocks_[n].type == "math_number") {
        //     code += "data_type_S.add(1)\n";
        // }
    }
    code += "String jsonString\n" +
        VarName + "_json_.printTo(jsonString)\n " +
        "server.send(200, \"application/json\", jsonString)\n"
    return code;
};

Blockly.Python['wifiServer_Receive'] = function(block) {
    var json_include = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("json_declaration", json_include);

    var varName = block.getFieldValue("VAR") || '';
    var length = block.getFieldValue("LENGTH") || '';
    var data_dec = "String data_" + varName + "[" + length + "]\n" +
        // "int dataType_" + varName + "[" + length + "]\n" +
        "";
    // for (let i = 0; i < length; i++) {
    //     data_dec += "0";
    //     if (i != length - 1) data_dec += ",";
    // }
    // data_dec += "}\n";
    Blockly.Python.addDeclaration("data_dec" + varName, data_dec);

    var Server_receiver = "void server_receiver_" + varName + "(String data) {" +
        "  StaticJsonBuffer<800> ParseBuffer_" + varName + "\n" +
        "  JsonObject& parse_" + varName + " = ParseBuffer_" + varName + ".parseObject(data)\n" +
        "  for (int i = 0; i < " + length + "; i++) {\n" +
        "    data_" + varName + "[i] = parse_" + varName + "[\"data\"][i].as<String>()\n" +
        // "    dataType_" + varName + "[i] = parse_" + varName + "[\"type\"][i].as<int>()\n" +
        "  }\n}\n";
    Blockly.Python.addFunction("Server_receiver_" + varName, Server_receiver);

    var code = "  String data = server.arg(\"plain\")\n" +
        "server_receiver_" + varName + "(data)\n" +
        "server.send(200,\"text/plain\",data)\n";
    return code;
};

Blockly.Python['wifiServer_Receive_getValue'] = function(block) {
    var varName = block.getFieldValue("VAR") || '';
    var index = block.getFieldValue("INDEX") || '';
    var type = block.getFieldValue("TYPE") || '';
    // var code = "dataType_" + varName + "[" + index + "] == 1 ? data_" + varName + "[" + index + "].toInt() : data_" + varName + "[" + index + "]";
    var code = "data_" + varName + "[" + index + "]"
    if (type == "Int") code += ".toInt()";
    return [code, Blockly.Python.ORDER_ATOMIC];
}