'use strict';

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

/* NBIoT
 * Setup
 */
Blockly.Python['NBIoT_setup'] = function(block) {
    Blockly.Python.addDeclaration("NBIoT_Dec", "#define nbiotSerial Serial1\n" +
        "int nbiotperiodicallyExecutionState = 0\n" +
        "int nbiotperiodicallyExecutionGap = 8\n" +
        "int serialSendState = 0\n")
    Blockly.Python.addSetup("NBIoT_Setup",
        "nbiotSerial.begin(115200)\n" +
        "nbiotSerial.write(\"AT+CSQ\\r\\n\")\n"
        /* "delay(3000)\n"+
        "nbiotSerial.write(\"AT+CMSYSCTRL=0,2,50,300,100,800\\r\\n\")\n"*/
    );
    return '';
}

/* NBIoT 
 * Http request
 */
Blockly.Python['NBIoT_http'] = function(block) {
    var apikey = block.getFieldValue("APIKEY");
    Blockly.Python.addFunction("nbiotHttprequestPOST", 'void nbiotHttprequestPOST() {\n' +
        '  int nbiotDataLength = nbiotHTTPJSONDataSet().length() + 1\n' +
        '  char nbiotDataBuf[nbiotDataLength]\n' +
        '  nbiotHTTPJSONDataSet().toCharArray(nbiotDataBuf, nbiotDataLength)\n' +

        /*'  if ( (millis() / 100) % (nbiotperiodicallyExecutionGap * 10) == ((nbiotperiodicallyExecutionGap * 10) - 1) && nbiotperiodicallyExecutionState == 0) {\n'+
        '    nbiotSerial.write("AT+HTTPCREATE=\\"http://api.cocorobo.cn/\\"\\r\\n")\n'+
        '    nbiotSerial.write("AT+HTTPHEADER=0,\\"Content-Type: application/json\\\\r\\\\n\\"\\r\\n")\n'+
        '    nbiotSerial.write(nbiotDataBuf)\n'+
        '    nbiotSerial.write("AT+HTTPSEND=0,1,\\"/iot/data/eventAPIKey/'+apikey+'\\"\\r\\n")\n'+
        '  } else if ((millis() / 100) % (nbiotperiodicallyExecutionGap * 10) == ((nbiotperiodicallyExecutionGap * 10) - 10)) {\n'+
        '    digitalWrite(13, LOW)\n'+
        // '    nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n'+
        '  }\n'+  */

        '  if ((millis() / 1000) % 10 == 1 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n' +
        '    serialSendState= 1\n;' +
        '  } else if ((millis() / 1000) % 10 == 2) {\n' +
        '    serialSendState = 0\n }' +
        '  if ((millis() / 1000) % 10 == 3 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPCREATE=\\"http://api.cocorobo.cn/\\"\\r\\n")\n' +
        '    nbiotSerial.write("AT+HTTPHEADER=0,\\"Content-Type: application/json\\\\r\\\\n\\"\\r\\n")\n' +
        '    serialSendState= 1\n' +
        '  } else if ((millis() / 1000) % 10 == 4) {\n' +
        '    serialSendState = 0\n }' +
        '  if ((millis() / 1000) % 10 == 5 && serialSendState == 0) {\n' +
        '    nbiotSerial.write(nbiotDataBuf)\n' +
        '    serialSendState= 1\n' +
        '  } else if ((millis() / 1000) % 10 == 6) {\n' +
        '    serialSendState = 0\n }' +
        '  if ((millis() / 1000) % 10 == 7 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPSEND=0,1,\\"/iot/data/eventAPIKey/' + apikey + '\\"\\r\\n")\n' +
        '    serialSendState= 1\n' +
        '  } else if ((millis() / 1000) % 10 == 8) {\n' +
        '    serialSendState = 0\n }' +
        '  }\n')

    var nbiotHTTPJSONDataSet = 'String nbiotHTTPJSONDataSet() {\n' +
        '  String data = "AT+HTTPCONTENT=0,\\"{"\n';
    for (var i = 0; i < block.itemCount_; i++) {
        var data_default = block.getFieldValue("DATA_DEFAULT" + i) || "default";
        var data_value = Blockly.Python.valueToCode(block, 'ADD' + i, Blockly.Python.ORDER_ATOMIC) || 0;
        if (i > 0) nbiotHTTPJSONDataSet += '  data += ","\n';
        nbiotHTTPJSONDataSet += '  data += "\\""\n' +
            '  data += "' + data_default + '"\n' +
            '  data += "\\":"\n' +
            // '  data += "\'"\n'+
            '  data += ' + data_value + '\n'
        // '  data += "\'"\n'
    }
    nbiotHTTPJSONDataSet += '  data += "}\\"\\r\\n"\n' +
        '  return data\n' +
        '}\n'
    Blockly.Python.addFunction("nbiotHTTPJSONDataSet", nbiotHTTPJSONDataSet);

    var code = "nbiotHttprequestPOST()\n";
    return code;
}

Blockly.Python['NBIoT_enable'] = function(block) {
    Blockly.Python.addDeclaration("nbiotEnable_var", 'const char EOPmarker = \'\\r\\n\'; //This is the end of packet marker\n' +
        'char serialbuf[200]; //This gives the incoming serial some room. Change it if you want a longer incoming.\n' +
        'char c = " "\n' +
        '\n' +
        'String nbiot_btstring\n' +
        'String nbiot_var\n' +
        'String nbiot_str\n' +
        '\n' +
        'int _stateADDR = 0\n' +
        'int _stateNbiotIsOn = 0\n' +
        'String _IPADDR = ""\n');
    Blockly.Python.addFunction("interactiveNBIoTSerial", 'void interactiveNBIoTSerial(){\n' +
        '  while (nbiotSerial.available() > 0) { //makes sure something is ready to be read\n' +
        '\n' +
        '    static int bufpos = 0; //starts the buffer back at the first position in the incoming serial.read\n' +
        '    char inchar = nbiotSerial.read(); //assigns one byte (as serial.read()\'s only input one byte at a time\n' +
        '    if (inchar != EOPmarker) { //if the incoming character is not the byte that is the incoming package ender\n' +
        '      serialbuf[bufpos] = inchar; //the buffer position in the array get assigned to the current read\n' +
        '      bufpos++; //once that has happend the buffer advances, doing this over and over again until the end of package marker is read.\n' +
        '    }\n' +
        '    else { //once the end of package marker has been read\n' +
        '      serialbuf[bufpos] = 0; //restart the buff\n' +
        '      bufpos = 0; //restart the position of the buff\n' +
        '\n' +
        '      Serial.println(serialbuf)\n' +
        '      nbiot_str = serialbuf\n' +
        '\n' +
        '      if (nbiot_str.charAt(1) == \'I\' && nbiot_str.charAt(2) == \'P\') {\n' +
        '        nbiot_var = midString(nbiot_str, "+IP:", "\\r")\n' +
        '        _IPADDR = nbiot_var\n' +
        '        int i = 0\n' +
        '        while (i < nbiot_var.length()) {\n' +
        '          if (nbiot_var.charAt(i) == \'.\') \n' +
        '            nbiot_var.setCharAt(i, \',\')\n' +
        '          i++\n' +
        '        }\n' +
        '        Serial.println(nbiot_var)\n' +
        '        _stateADDR = 1\n' +
        '      }\n' +
        'if (nbiot_str.charAt(1) == \'C\' && nbiot_str.charAt(2) == \'P\' && nbiot_str.charAt(3) == \'I\' && nbiot_str.charAt(4) == \'N\' && nbiot_str.charAt(7) == \'R\' && nbiot_str.charAt(8) == \'E\' && nbiot_str.charAt(9) == \'A\' && nbiot_str.charAt(10) == \'D\' && nbiot_str.charAt(11) == \'Y\') {\n' +
        '_stateNbiotIsOn = 1\n' +
        'Serial.println("NBIoT initiated.")\n' +
        'delay(100)\n' +
        'nbiotSerial.write("AT+CMSYSCTRL=0,2,50,300,100,800\\r\\n")\n' +
        '}\n' +
        '\n' +
        '    }\n' +
        '  }\n' +
        '  while (Serial.available() > 0) {\n' +
        '    char cmd = Serial.read()\n' +
        '    nbiotSerial.write(cmd)\n' +
        '  }\n' +
        '}\n');

    Blockly.Python.addFunction("NBIoT_midString", "String midString(String str, String start, String finish) {\n" +
        "  int locStart = str.indexOf(start)\n" +
        "  if (locStart == -1) return \"\"\n" +
        "  locStart += start.length()\n" +
        "  int locFinish = str.indexOf(finish, locStart)\n" +
        "  if (locFinish == -1) return \"\"\n" +
        "  return str.substring(locStart, locFinish)\n" +
        "}\n");

    var code = "interactiveNBIoTSerial()\n";
    return code;
}

/* NBIoT 
 * Http request
 */
Blockly.Python['NBIoT_http_thingspeak'] = function(block) {
    var apikey = block.getFieldValue("APIKEY");
    var get_str = 'update?api_key=' + apikey + '&';
    for (let i = 0; i < block.itemCount_; i++) {
        var data_item = Blockly.Python.valueToCode(block, "ADD" + i, Blockly.Python.ORDER_ATOMIC);
        get_str += 'field' + (i + 1) + '="+String(' + data_item + ')+"'
        if (i != block.itemCount_ - 1) get_str += '&';
        //  else  get_str += '"';
    }

    Blockly.Python.addFunction("nbiotThingspeakRequest", 'void nbiotThingspeakRequest() {\n' +
        '   if ((millis() / 1000) % 10 == 1 && serialSendState == 0) {\n' +
        '     nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n' +
        '     serialSendState= 1\n;' +
        '   } else if ((millis() / 1000) % 10 == 2) {\n' +
        '     serialSendState = 0\n' +
        '   }\n' +
        '   if ((millis() / 1000) % 10 == 3 && serialSendState == 0) {\n' +
        '     nbiotSerial.write("AT+HTTPCREATE=\\"http://api.thingspeak.com/\\"\\r\\n")\n' +
        '     nbiotSerial.write("AT+HTTPHEADER=0,\\"User-Agent: Unknown\\\\r\\\\n\\"\\r\\n")\n' +
        '     serialSendState= 1\n' +
        '   } else if ((millis() / 1000) % 10 == 4) {\n' +
        '     serialSendState = 0\n' +
        '   }\n' +
        '   if ((millis() / 1000) % 10 == 5 && serialSendState == 0 ){\n' +
        '     String myString = "AT+HTTPSEND=0,0,\\"' + get_str + '\\"\\r\\n"\n' +
        '     char* buf = (char*) malloc(sizeof(char)*myString.length()+1)\n' +
        '     myString.toCharArray(buf, myString.length()+1)\n' +
        '     nbiotSerial.write(buf)\n' +
        '     serialSendState= 1\n' +
        '   } else if ((millis() / 1000) % 10 == 6) {\n' +
        '     serialSendState = 0\n' +
        '   }\n' +
        '}\n')

    var code = "nbiotThingspeakRequest()\n";
    return code;
}


/* NBIoT 
 * Http request
 */
Blockly.Python['NBIoT_http_IFTTT'] = function(block) {
    var apikey = block.getFieldValue("APIKEY");
    var event = block.getFieldValue("EVENT");
    var get_str = 'update?api_key=' + apikey + '&';
    for (let i = 0; i < block.itemCount_; i++) {
        var data_item = Blockly.Python.valueToCode(block, "ADD" + i, Blockly.Python.ORDER_ATOMIC);
        get_str += 'field' + (i + 1) + '="+String(' + data_item + ')+"'
        if (i != block.itemCount_ - 1) get_str += '&';
        //  else  get_str += '"';
    }

    Blockly.Python.addFunction("nbiotIFTTTRequest", 'void nbiotIFTTTRequest() {\n' +
        '  int nbiotDataLength = nbiotHTTPJSONDataSet().length() + 1\n' +
        '  char nbiotDataBuf[nbiotDataLength]\n' +
        '  nbiotHTTPJSONDataSet().toCharArray(nbiotDataBuf, nbiotDataLength)\n' +

        /*'  if ( (millis() / 100) % (nbiotperiodicallyExecutionGap * 10) == ((nbiotperiodicallyExecutionGap * 10) - 1) && nbiotperiodicallyExecutionState == 0) {\n'+
        '    nbiotSerial.write("AT+HTTPCREATE=\\"http://api.cocorobo.cn/\\"\\r\\n")\n'+
        '    nbiotSerial.write("AT+HTTPHEADER=0,\\"Content-Type: application/json\\\\r\\\\n\\"\\r\\n")\n'+
        '    nbiotSerial.write(nbiotDataBuf)\n'+
        '    nbiotSerial.write("AT+HTTPSEND=0,1,\\"/iot/data/eventAPIKey/'+apikey+'\\"\\r\\n")\n'+
        '  } else if ((millis() / 100) % (nbiotperiodicallyExecutionGap * 10) == ((nbiotperiodicallyExecutionGap * 10) - 10)) {\n'+
        '    digitalWrite(13, LOW)\n'+
        // '    nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n'+
        '  }\n'+  */

        'if ((millis() / 1000) % 10 == 1 && serialSendState == 0) {\n' +
        '  nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n' +
        '  serialSendState= 1\n;' +
        '} else if ((millis() / 1000) % 10 == 2) {\n' +
        '  serialSendState = 0\n }' +

        'if ((millis() / 1000) % 10 == 3 && serialSendState == 0) {\n' +
        '  nbiotSerial.write("AT+HTTPCREATE=\\"http://maker.ifttt.com/\\"\\r\\n")\n' +
        '  nbiotSerial.write("AT+HTTPHEADER=0,\\"Content-Type: application/json\\\\r\\\\n\\"\\r\\n")\n' +
        '  serialSendState= 1\n' +
        '} else if ((millis() / 1000) % 10 == 4) {\n' +
        '  serialSendState = 0\n }' +

        'if ((millis() / 1000) % 10 == 5 && serialSendState == 0) {\n' +
        '  nbiotSerial.write(nbiotDataBuf)\n' +
        '  serialSendState= 1\n' +
        '} else if ((millis() / 1000) % 10 == 6) {\n' +
        '  serialSendState = 0\n }' +

        'if ((millis() / 1000) % 10 == 7 && serialSendState == 0) {\n' +
        '  nbiotSerial.write("AT+HTTPSEND=0,1,\\"/trigger/' + event + '/with/key/' + apikey + '\\"\\r\\n")\n' +
        '  serialSendState= 1\n' +
        '} else if ((millis() / 1000) % 10 == 8) {\n' +
        '  serialSendState = 0\n }' +

        '}\n')

    var nbiotHTTPJSONDataSet = 'String nbiotHTTPJSONDataSet() {\n' +
        '  String data = "AT+HTTPCONTENT=0,\\"{"\n';
    for (var i = 0; i < block.itemCount_ && i < 3; i++) {
        var data_default = "value" + (i + 1)
        var data_value = Blockly.Python.valueToCode(block, 'ADD' + i, Blockly.Python.ORDER_ATOMIC) || 0;
        if (i > 0) nbiotHTTPJSONDataSet += '  data += ","\n';
        nbiotHTTPJSONDataSet += '  data += "\\""\n' +
            '  data += "' + data_default + '"\n' +
            '  data += "\\":"\n' +
            // '  data += "\'"\n'+
            '  data += ' + data_value + '\n'
        // '  data += "\'"\n'
    }
    nbiotHTTPJSONDataSet += '  data += "}\\"\\r\\n"\n' +
        '  return data\n' +
        '}\n'
    Blockly.Python.addFunction("nbiotHTTPJSONDataSet", nbiotHTTPJSONDataSet);
    var code = "nbiotIFTTTRequest()\n";
    return code;
}


Blockly.Python['NBIoT_network_connected'] = function(block) {
    var code = "_stateADDR";
    return [code, Blockly.Python.ORDER_ATOMIC]
}

Blockly.Python['NBIoT_powered_on'] = function(block) {
    var code = "_stateNbiotIsOn";
    return [code, Blockly.Python.ORDER_ATOMIC]
}

Blockly.Python['NBIoT_network_IP'] = function(block) {
    var code = "_IPADDR";
    return [code, Blockly.Python.ORDER_ATOMIC]
}

Blockly.Python['NBIoT_http_cococloud_get'] = function(block) {
    var apikey = block.getFieldValue("APIKEY") || '';
    Blockly.Python.addFunction("nbiotHttprequestGet", 'void nbiotHttprequestGet() {\n' +
        '  char nbiotDataBuf[nbiotDataLength]\n' +
        '  if ((millis() / 1000) % 10 == 1 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPCLOSE=0\\r\\n")\n' +
        '    serialSendState= 1\n;' +
        '  } else if ((millis() / 1000) % 10 == 2) {\n' +
        '    serialSendState = 0\n }' +
        '  if ((millis() / 1000) % 10 == 3 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPCREATE=\\"http://api.cocorobo.cn/\\"\\r\\n")\n' +
        '    nbiotSerial.write("AT+HTTPHEADER=0,\\"User-Agent: Unknown\\r\\n\\"\\r\\n")\n' +
        '    serialSendState= 1\n' +
        '  } else if ((millis() / 1000) % 10 == 4) {\n' +
        '    serialSendState = 0\n }' +
        '  if ((millis() / 1000) % 10 == 5 && serialSendState == 0) {\n' +
        '    nbiotSerial.write("AT+HTTPSEND=0,0,\\"/iot/data/eventAPIKey/' + apikey + '\\"\\r\\n")\n' +
        '    serialSendState= 1\n' +
        '  } else if ((millis() / 1000) % 10 == 6) {\n' +
        '    serialSendState = 0\n }' +
        '  }\n')
    var code = "";
    return code;
}