'use strict';

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

var eventIdentifier = '';

Blockly.Python['wifiwebservices_ifttt_simple'] = function(block) {
    var key = Blockly.Python.valueToCode(block, 'KEY', Blockly.Python.ORDER_ATOMIC).replace(/\"/g, '') || "";
    var event = Blockly.Python.valueToCode(block, 'EVENT', Blockly.Python.ORDER_ATOMIC).replace(/\"/g, '') || "";
    var value1 = Blockly.Python.valueToCode(block, 'VALUE1', Blockly.Python.ORDER_ATOMIC) || "";
    var value2 = Blockly.Python.valueToCode(block, 'VALUE2', Blockly.Python.ORDER_ATOMIC) || "";
    var value3 = Blockly.Python.valueToCode(block, 'VALUE3', Blockly.Python.ORDER_ATOMIC) || "";
    var jsontool_declaration = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("jsontool_declaration", jsontool_declaration);
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude("wifi_httpclient", wifi_httpclient);
    var httpclient = "HTTPClient http;";
    Blockly.Python.addDeclaration("httpclient", httpclient);
    var precode = "char JSONmessageBuffer[240]\n";
    Blockly.Python.addDeclaration("jsontool_prettyPrint", precode);
    var url = "http://maker.ifttt.com/trigger/" + event + "/with/key/" + key;
    var code = "StaticJsonBuffer<800> JSONbuffer\n" +
        "JsonObject& JSONencoder = JSONbuffer.createObject()\n" +
        "JSONencoder[\"value1\"] = String(" + value1 + ")\n" +
        "JSONencoder[\"value2\"] = String(" + value2 + ")\n" +
        "JSONencoder[\"value3\"] = String(" + value3 + ")\n" +
        "JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer))\n" +
        "Serial.println(JSONmessageBuffer)\n" +
        "if (WiFi.status() == WL_CONNECTED) {\n" +
        "  http.begin(\"" + url + "\")\n" +
        "  http.addHeader(\"Content-Type\", \"application/json\")\n" +
        "  int httpCode = http.POST(JSONmessageBuffer)\n" +
        "  String payload = http.getString()\n" +
        "  // Serial.println(httpCode)\n" +
        "  // Serial.println(payload)\n" +
        "  http.end()\n" +
        // "  delay(500)\n" +
        "} else {\n" +
        "  Serial.println(\"Error in WiFi connection\")\n" +
        "}\n";
    return code;
};

Blockly.Python['wifiwebservices_thinkspeak_simple'] = function(block) {
    var key = Blockly.Python.valueToCode(block, 'KEY', Blockly.Python.ORDER_ATOMIC).replace(/\"/g, '') || "";
    var size = block.itemCount_;
    var item_field = '',
        item_value = '';
    var thingspeak_url = "http://api.thingspeak.com/update?api_key=" + key;
    for (var n = 0; n < this.itemCount_; n++) {
        item_field = block.getFieldValue('FIELD' + n);
        item_value = Blockly.Python.valueToCode(this, 'ADD' + n,
            Blockly.Python.ORDER_NONE) || '';
        thingspeak_url += '&' + item_field + '=\"+String(' + item_value + ')+\"';
    }
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude("wifi_httpclient", wifi_httpclient);
    Blockly.Python.addDeclaration("httpclient", "HTTPClient http;");
    var code = "http.begin(\"" + thingspeak_url + "\")\n" +
        "http.GET()\n" +
        "http.end()\n" +
        "delay(500)\n";
    return code;
};

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


Blockly.Python['wifiServices_thingspeak'] = function(block) {
    var key = block.getFieldValue("API_KEY");
    var item_field = '',
        item_value = '';
    var thingspeak_url = "http://api.thingspeak.com/update?api_key=" + key;
    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 + '=\"+String(' + item_value + ')+\"';
    }
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude("wifi_httpclient", wifi_httpclient);
    Blockly.Python.addDeclaration("httpclient", "HTTPClient http;");
    var code = "http.begin(\"" + thingspeak_url + "\")\n" +
        "http.GET()\n" +
        "http.end()\n" +
        "delay(500)\n";
    return code;
};

Blockly.Python['wifiServices_IFTTT'] = function(block) {

    var jsontool_declaration = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("jsontool_declaration", jsontool_declaration);
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude("wifi_httpclient", wifi_httpclient);
    var httpclient = "HTTPClient http;";
    Blockly.Python.addDeclaration("httpclient", httpclient);
    var HTTPCode = "int httpCode;";
    Blockly.Python.addDeclaration('HTTP_code', HTTPCode);
    Blockly.Python.addDeclaration("payload", "String payload;");
    var precode = "char JSONmessageBuffer[240]\n";
    Blockly.Python.addDeclaration("jsontool_prettyPrint", precode);

    var key = block.getFieldValue('IFTTT_KEY').replace(/\"/g, '') || "";
    var event = block.getFieldValue('IFTTT_EVENT').replace(/\"/g, '') || "";
    var url = "http://maker.ifttt.com/trigger/" + event + "/with/key/" + key;
    var type = block.getType();
    block.onChange();
    if (type == 2) {
        var code = "if (WiFi.status() == WL_CONNECTED) {\n" +
            "  if ((millis() % 1000) /100  % 5 == 0 ) {\n" +
            "    http.begin(\"" + url + "\")\n" +
            "    httpCode = http.GET()\n" +
            "    payload = http.getString()\n" +
            "    // Serial.println(httpCode)\n" +
            "    // Serial.println(payload)\n" +
            "    http.end()\n" +
            "  }\n" +
            // "  delay(500)\n" +
            "} else {\n" +
            "  Serial.println(\"Error in WiFi connection\")\n" +
            "}\n";
    } else if (type == 1) {
        var value1 = Blockly.Python.valueToCode(block, 'data0', Blockly.Python.ORDER_ATOMIC) || "";
        var value2 = Blockly.Python.valueToCode(block, 'data1', Blockly.Python.ORDER_ATOMIC) || "";
        var value3 = Blockly.Python.valueToCode(block, 'data2', Blockly.Python.ORDER_ATOMIC) || "";
        var code = "" +
            // "if ((millis() % 1000) /100  % 5 == 0 ) {\n" +
            "  StaticJsonBuffer<800> JSONbuffer_ifttt\n" +
            "  JsonObject& JSONencoder = JSONbuffer_ifttt.createObject()\n" +
            "  JSONencoder[\"value1\"] = String(" + value1 + ")\n" +
            "  JSONencoder[\"value2\"] = String(" + value2 + ")\n" +
            "  JSONencoder[\"value3\"] = String(" + value3 + ")\n" +
            "  JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer))\n" +
            "  Serial.println(JSONmessageBuffer)\n" +
            "  if (WiFi.status() == WL_CONNECTED) {\n" +
            "    http.begin(\"" + url + "\")\n" +
            "    http.addHeader(\"Content-Type\", \"application/json\")\n" +
            "    httpCode = http.POST(JSONmessageBuffer)\n" +
            "    payload = http.getString()\n" +
            "    Serial.println(httpCode)\n" +
            "    Serial.println(payload)\n" +
            "    http.end()\n" +
            "    delay(500)\n" +
            "  } else {\n" +
            "    Serial.println(\"Error in WiFi connection\")\n" +
            "  }\n"
            // "}\n";
    }
    return code;
}

Blockly.Python['wifiServices_cococloud_post'] = function(block) {
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude('wifi_httpclient', wifi_httpclient);
    var HTTPResponse = "String http_response;";
    Blockly.Python.addDeclaration('HTTP_Response', HTTPResponse);
    var HTTPCode = "int httpCode;";
    Blockly.Python.addDeclaration('HTTP_code', HTTPCode);
    let serial_setup = "Serial.begin(9600);";
    Blockly.Python.addSetup('serial_serial', serial_setup);
    var httpclient = "HTTPClient http;";
    Blockly.Python.addDeclaration("httpclient", httpclient);
    Blockly.Python.addDeclaration("payload", "String payload;");
    var json_include = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("json_declaration", json_include);
    var precode = "char JSONmessageBuffer[240]\n";
    Blockly.Python.addDeclaration("jsontool_prettyPrint", precode);

    var code = "";
    var item_url = "http://api.cocorobo.cn/iot/data/eventAPIKey/" + block.getFieldValue("event0");
    // var item_url = "http://staging.cocorobo.cn/api/iot/data/eventAPIKey/" + block.getFieldValue("event0"); //staging
    var code = "StaticJsonBuffer<800> JSONbuffer_easymode\n" +
        "JsonObject& Json_easymode = JSONbuffer_easymode.createObject()\n";
    for (var n = 0; n < this.itemCount_; n++) {
        var item_field = block.getFieldValue("field" + n);
        var item_value = Blockly.Python.valueToCode(this, 'ADD' + n,
            Blockly.Python.ORDER_NONE) || '0';
        code += "Json_easymode[\"" + item_field + "\"]=" + item_value + "\n";
    }
    code += "" +
        "if ((millis() % 1000) /100  % 5 == 0 ) {\n" +
        "  Json_easymode.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer))\n" +
        "  http.begin(\"" + item_url + "\")\n" +
        "  http.addHeader(\"Content-Type\", \"application/json\")\n" +
        "  httpCode = http.POST(JSONmessageBuffer)\n" +
        "  payload = http.getString()\n" +
        "  Serial.println(httpCode)\n" +
        "  Serial.println(payload)\n" +
        "  http.end()\n" +
        "}\n"
        // "delay(500)\n";
    return code;
}

Blockly.Python['wifiServices_cococloud_get'] = function(block) {
    var wifi_httpclient = "#include <ESP8266HTTPClient.h>";
    Blockly.Python.addInclude('wifi_httpclient', wifi_httpclient);
    var HTTPResponse = "String http_response;";
    Blockly.Python.addDeclaration('HTTP_Response', HTTPResponse);
    var HTTPCode = "int httpCode;";
    Blockly.Python.addDeclaration('HTTP_code', HTTPCode);
    let serial_setup = "Serial.begin(9600);";
    Blockly.Python.addSetup('serial_serial', serial_setup);
    var httpclient = "HTTPClient http;";
    Blockly.Python.addDeclaration("httpclient", httpclient);
    var cococloud_Response = "String cococloud_response;";
    Blockly.Python.addDeclaration("cococloud_Response", cococloud_Response);
    Blockly.Python.addDeclaration("payload", "String payload;");
    var json_include = "#include <ArduinoJson.h>";
    Blockly.Python.addInclude("json_declaration", json_include);

    var code = "";
    var item_url = "http://api.cocorobo.cn/iot/data/eventAPIKey/" + block.getFieldValue("event0");
    // var item_url = "http://staging.cocorobo.cn/api/iot/data/eventAPIKey/" + block.getFieldValue("event0"); //staging
    var dataGet, item_value;

    eventIdentifier = block.getFieldValue("event0").slice(0, 5);

    code += "" +
        "if ((millis() % 1000) /100  % 5 == 0 ) {\n" +
        "  http.begin(\"" + item_url + "\")\n" +
        "  http.addHeader(\"Content-Type\", \"application/json\")\n" +
        "  httpCode = http.GET()\n" +
        "  payload = http.getString()\n" +
        "  cococloud_response = payload\n" +
        "  // Serial.println(httpCode)\n" +
        "  // Serial.println(payload)\n" +
        "  http.end()\n" +
        "}\n" +
        // "delay(500)\n" +
        "StaticJsonBuffer<800> jsonBuffer_easymode_" + block.getFieldValue("event0").slice(0, 5) + "\n" +
        "JsonObject& cloud_data_" + block.getFieldValue("event0").slice(0, 5) + "  =  jsonBuffer_easymode_" + block.getFieldValue("event0").slice(0, 5) + ".parseObject(cococloud_response)\n";
    for (var n = 0; n < this.itemCount_; n++) {
        dataGet = Blockly.Python.variableDB_.getName(
            block.getFieldValue('DATA' + n), Blockly.Variables.NAME_TYPE);
        item_value = Blockly.Python.valueToCode(this, 'ADD' + n,
            Blockly.Python.ORDER_NONE) || '""';
        code += "" + dataGet + "=" + item_value + "\n";
    }
    return code;
}

Blockly.Python['wifiServices_cococloud_get_data'] = function(block) {
    var code = "";
    var key = block.getFieldValue("KEY");
    var varType = block.getFieldValue('VAR_TYPE');
    if (varType == "Text") {
        varType = "char*";
    } else if (varType == "Number") {
        varType = "int";
        // } else if (varType == "Boolean") {
        //     varType = "boolean";
        // } else if (varType == "Large Number") {
        //     varType = "long";
        // } else if (varType == "Decimal") {
        //     varType = "float";
    }
    code = "cloud_data_" + eventIdentifier + "[\"data\"][0][\"" + key + "\"].as<" + varType + ">()";
    return [code, Blockly.Python.ORDER_ATOMIC];
}