var updates = "";

Blockly.Lua['createsensorsketch'] = function(block) {
  var statements = Blockly.Lua.statementToCode(block, 'NAME');
  var Imports = "--Initialize as station\nwifi.setmode(wifi.STATION)\n";
  var Imports = Imports + "--Global Variables--\n";
  // Variables 
  if (statements.indexOf ( 'joinNetwork()') > -1) {
     Imports = Imports + "SSID = \'\'\n";
     Imports = Imports + "Password = \'\'\n";
     Imports = Imports + "filename = \'ssidPassword.txt\'\n";
     Imports = Imports + "ServerAddress = \'172.24.1.1\'\n";
     Imports = Imports + "MAC = wifi.sta.getmac()\n";
  }

  Imports = Imports + "CurrentValue = \'0\'\n";

  // Functions 
  Imports = Imports + "\n--Functions--\n"
  Imports = Imports + "function trim(s)\n"
  Imports = Imports + "  return (s:gsub(\"^%s*(.-)%s*$\", \"%1\"))\n";
  Imports = Imports + "end --trim\n\n";
 
  Imports = Imports + "function extractServerCommand (command) \n";
  Imports = Imports + "  serverCommand = \"\"\n";
  Imports = Imports + "  -- Check command from the server\n";
  Imports = Imports + "  if string.sub(command,1,7) == \"turn on\" then\n";
  Imports = Imports + "    serverCommand = \"turn on\"\n";
  Imports = Imports + "  elseif string.sub(command,1,8) == \"turn off\" then\n";
  Imports = Imports + "    serverCommand = \"turn off\"\n";
  Imports = Imports + "  else\n";
  Imports = Imports + "    print (\"Server command not understood:\"..command)\n";
  Imports = Imports + "  end\n";
  Imports = Imports + "  return serverCommand\n";
  Imports = Imports + "end -- extractServerCommand\n\n";
  
  Imports = Imports + "function extractRelayNumber ( command, startIndex )\n"; 
  Imports = Imports + "  relayNumber = -1\n";
  Imports = Imports + "  tens = string.sub(command,startIndex,startIndex)\n"; 
  Imports = Imports + "  gpioNumber = string.byte(tens)-48\n"; 
  Imports = Imports + "  if (gpioNumber >= 0) and (gpioNumber <= 9) then \n";
  Imports = Imports + "    relayNumber = gpioNumber\n";
  Imports = Imports + "    ones = string.sub(command,startIndex+1,startIndex+1)\n";
  Imports = Imports + "    val = string.byte(ones) - 48\n";
  Imports = Imports + "    if (val >= 0) and (val <= 9) then \n";
  Imports = Imports + "      relayNumber = (gpioNumber * 10) + val\n";
  Imports = Imports + "    end\n";
  Imports = Imports + "  end\n";
  Imports = Imports + "  return relayNumber\n"; 
  Imports = Imports + "end -- extractRelayNumber \n\n";   
  
  if (statements.indexOf ( 'sendHeartbeat') > -1) {
   Imports = Imports + "-- Send hearbeat message from esp8266 to the raspberry pi server\n";
   Imports = Imports + "function sendHeartbeat()\n"; 
   Imports = Imports + "  sk=net.createConnection(net.TCP, 0)\n";
   Imports = Imports + "  sk:on(\"receive\", function(sk, c) print(c) end )\n";  
   Imports = Imports + "  -- When the connection is established, send the data\n";
   Imports = Imports + "  sk:on(\"connection\", function(sck)\n"; 
   Imports = Imports + "                          print (\"Connected,sending\"..msg)\n";
   Imports = Imports + "                          sck:send(msg)\n"; 
   Imports = Imports + "                        end )\n";
   Imports = Imports + "  -- When the data is sent\n";
   Imports = Imports + "  sk:on(\"sent\",function(sk)\n";
   Imports = Imports + "                   print(\"Data Sent!\")\n";
   Imports = Imports + "                   sk:close()\n";
   Imports = Imports + "                   sk=nil\n";
   Imports = Imports + "                 end )\n";    
   Imports = Imports + "  msg = \"GET /Paulware/updateSensor.php?MAC=\"..MAC..\"&value=\"..CurrentValue..\" HTTP/1.1\\r\\nHost: Paulware\\r\\nConnection: keep-alive\\r\\nAccept: */*\\r\\n\\r\\n\"\n";
   Imports = Imports + "  sk:connect(80,ServerAddress)\n"; 
   Imports = Imports + "end --sendHeartbeat\n\n";
  }  
  if (statements.indexOf ( "listenForServerCommand") > -1) {
   Imports = Imports + "function listenForServerCommand()\n";
   Imports = Imports + "  port = 3333\n"; 
   Imports = Imports + "  srv=net.createServer(net.UDP)\n";
   Imports = Imports + "  srv:on(\"receive\", function(connection, pl)\n";
   Imports = Imports + "    print(\"Command Received \"..pl)\n";
   Imports = Imports + "    -- Get server address\n";
   Imports = Imports + "    if string.sub (pl,1,6) == \"server\" then\n";
   Imports = Imports + "      print (\"Server address received.\")\n";       
   Imports = Imports + "      ServerAddress = string.sub (pl, 8)\n"; 
   Imports = Imports + "      print (\"Address:\"..ServerAddress..\".\" )\n";
   Imports = Imports + "    else\n";
   Imports = Imports + "      -- Note: handleServerCommand must be defined by user\n"
   Imports = Imports + "      handleServerCommand (pl)\n";   
   Imports = Imports + "    end\n";
   Imports = Imports + "  end)\n";
   Imports = Imports + "  srv:listen(port)\n";   
   Imports = Imports + "end -- listenForServerCommand\n\n";    
  }
  if (statements.indexOf ( "joinNetwork") > -1) {	 
    Imports = Imports + "function login (ssid,password)\n";
    Imports = Imports + "  print (\"ssid: \"..ssid..\" password: \"..password)\n"; 
    Imports = Imports + "  print (\"Save SSID/Password to text.txt\" )\n";
    Imports = Imports + "  file.open (filename, \"w\")\n";
    Imports = Imports + "  file.writeline (ssid)\n";
    Imports = Imports + "  file.writeline (password)\n";
    Imports = Imports + "  file.close()\n";
    Imports = Imports + "  joinNetwork()\n";
    Imports = Imports + "end -- login\n\n";   
	   Imports = Imports + "function readSSIDPassword()\n"; 
    Imports = Imports + "  print(\"MAC: \"..MAC)\n";
    Imports = Imports + "  handle = file.open (filename, \"r\")\n";
    Imports = Imports + "  if handle == nil then\n";
	   Imports = Imports + "    print (\"SSID file does not exist yet, use the command: login (SSID,password)\" )\n";
    Imports = Imports + "  else\n";
    Imports = Imports + "    SSID = trim(file.readline())\n";
    Imports = Imports + "    Password = trim(file.readline())\n";
    Imports = Imports + "    file.close()\n";
    Imports = Imports + "    print (\"SSID:\"..SSID..\" Password:\"..Password )\n";
    Imports = Imports + "  end\n";   
    Imports = Imports + "end -- readSSIDPassword\n\n"; 
  }
  if (statements.indexOf ( 'joinNetwork()') > -1) {
    Imports = Imports + "function joinNetwork()\n";
    Imports = Imports + "  readSSIDPassword()\n";
    Imports = Imports + "  tmr.stop(1)\n";
    Imports = Imports + "  if (SSID ~= nil) and (Password ~= nil) then\n";
    Imports = Imports + "    print (\"system will now try to join network\" )\n";
    Imports = Imports + "    wifi.sta.config(SSID, Password)\n";
    Imports = Imports + "    ip = wifi.sta.getip()\n";
    Imports = Imports + "    if ip == nil then\n";
    Imports = Imports + "      print (\"Did not get assigned an ip address, try again in 20 seconds...\")\n";
    Imports = Imports + "      tmr.alarm(1, 20000, 1, joinNetwork)\n";
    Imports = Imports + "    else\n"; 
    Imports = Imports + "      print (\"I was assigned the ip address:\"..ip)\n";
    Imports = Imports + "    end\n";
    Imports = Imports + "  else\n";
    Imports = Imports + "    print (\"Please use login(SSID,password) command to set SSID & Password\" );\n";
    Imports = Imports + "    tmr.alarm (1,20000,1,joinNetwork)\n";      
    Imports = Imports + "  end\n";   
    Imports = Imports + "end -- joinNetwork\n\n";
  }

  var code = Imports + "\n--Sensor Sketch--\n" + statements + '\n';
  return code;
};

function getTypeName (value) {
  var bracket1 = findIndex ( value, '|', 1) + 1;
  var bracket2 = findIndex ( value, '|', 2);	
  var typeName = value.substring(bracket1,bracket2);
  return typeName;
}

function getUniqueName (value) {
  var bracket1 = findIndex ( value, '|', 2) + 1;
  var bracket2 = findIndex ( value, '|', 3);	
  var uniqueName = value.substring(bracket1,bracket2);
  var index = uniqueName.indexOf ( "\"");
  if (index != -1) {
	 uniqueName = uniqueName.substring (1,uniqueName.length-1);
  }
  return uniqueName;
}

function getPins (value) {
  var bracket1 = findIndex ( value, '|', 3) + 1;
  var bracket2 = findIndex ( value, '|', 4);	
  var val = value.substring(bracket1,bracket2);
  return val;
}

function findType (value) {
  var startIndex = value.indexOf ( '(' ) + 1;
  var endIndex = value.indexOf ( '|' );
  var library = value.substring ( startIndex,endIndex);
  return library;
}

function insideParen (value) {   
  var startIndex = value.indexOf ( '(' );
  if (startIndex == -1) {
     newValue = value;   
  } else {
    startIndex = startIndex + 1;
    var endIndex = value.indexOf ( ')' );
    var newValue = value.substring (startIndex, endIndex );
    if (newValue.indexOf ( '(' ) > -1) {
      endIndex = value.indexOf ( ')', endIndex + 1);
      newValue = value.substring (startIndex, endIndex );   
    }      
  }
  return newValue;
}

function insideChars (value, char1, char2) {
  var startIndex = value.indexOf (char1) + 1;
  var endIndex = value.indexOf ( char2, startIndex );
  var newValue = value.substring (startIndex, endIndex );
  return newValue;
}

function findIndex ( value, char, which ) {
  var startIndex = -1;
  var index;
  for (i=0; i<which; i++) {
    index = value.indexOf ( char, startIndex + 1);
    startIndex = index;
  }
  return index;
}

Blockly.Lua['getmacaddress'] = function(block) {
  var code = 'wifi.sta.getmac()';
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['serveraddressunknown'] = function(block) {
  var code = 'serverAddress == nil';
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['sendvalue'] = function(block) {
  var val = Blockly.Lua.valueToCode(block, 'VALUE', Blockly.Lua.ORDER_ATOMIC);
  var value = insideChars (val, "'", "'");
  code = "sendValue(" + value + ")\n";  
  return code;
};

Blockly.Lua['createtimer'] = function(block) {
  var whichTimer = block.getFieldValue('whichTimer');
  var name = Blockly.Lua.valueToCode(block, 'FUNCTIONNAME', Blockly.Lua.ORDER_ATOMIC);
  var functionName = insideChars (name, "'", "'");
  var timeout = Blockly.Lua.valueToCode(block, 'TIMEOUT', Blockly.Lua.ORDER_ATOMIC);
  var code = 'tmr.stop(' + whichTimer + ')\ntmr.alarm(' + whichTimer + ',' + timeout + ', 1, ' + functionName + ')\n';
  return code;
};

Blockly.Lua['nil'] = function(block) {
  var code = 'nil';
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['getipaddress'] = function(block) {
  var code = 'wifi.sta.getip()';
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['setmode'] = function(block) {
  var mode = block.getFieldValue('MODE');
  var pin = block.getFieldValue('PIN');
  var code = 'gpio.mode (' + pin + ', gpio.';
  if (mode == 'OUTPUT') {
    code = code + 'OUTPUT)\n'; 
  } else {
    code = code + 'INPUT)\n';
  }
  return code;
};

Blockly.Lua['substring'] = function(block) {
  var name = Blockly.Lua.valueToCode(block, 'NAME', Blockly.Lua.ORDER_ATOMIC);
  var startIndex = Blockly.Lua.valueToCode(block, 'START', Blockly.Lua.ORDER_ATOMIC);
  var stopIndex = Blockly.Lua.valueToCode(block, 'STOP', Blockly.Lua.ORDER_ATOMIC);
  var varName = insideChars ( name,"'","'")
  var code = 'string.sub(' + varName + ','+ startIndex 
  if (stopIndex != '') {
     code = code + ',' + stopIndex + ')';
  } else {
     code = code + stopIndex + ')';
  }
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['setgpio'] = function(block) {
  var value = Blockly.Lua.valueToCode(block, 'VALUE', Blockly.Lua.ORDER_ATOMIC);
  var pin = Blockly.Lua.valueToCode(block, 'PIN', Blockly.Lua.ORDER_ATOMIC);
  var code = 'gpio.write (' + pin + ',';
  if (value == 0) {
     code = code + 'gpio.LOW)\n'; 
  } else {
     code = code + 'gpio.HIGH)\n';
  }
  return code;
};

Blockly.Lua['ord'] = function(block) {
  var value = Blockly.Lua.valueToCode(block, 'VALUE', Blockly.Lua.ORDER_ATOMIC);
  var code = 'string.byte(' + value + ')';
  return [code, Blockly.Lua.ORDER_NONE];
};


Blockly.Lua['readssidpassword'] = function(block) {
  var code = "readSSIDPassword()\n"
  return code;
};

Blockly.Lua['listenforservercommand'] = function(block) {
  var code = "listenForServerCommand()\n"
  return code;
};

Blockly.Lua['joinnetwork'] = function(block) {
  var code = "joinNetwork()\n"
  return code;
};

Blockly.Lua['comment'] = function(block) {
  var comment = Blockly.Lua.valueToCode(block, 'COMMENT', Blockly.Lua.ORDER_ATOMIC);  
  var value = insideChars ( comment, "\'", "\'" );
  var code = '--' + value + '\n';
  return code;
};

Blockly.Lua['turnoff'] = function(block) {
  var variable = Blockly.Lua.valueToCode(block, 'VARIABLE', Blockly.Lua.ORDER_ATOMIC);
  var varName = insideChars ( variable,"'","'")
  var code = "turnOff(" + varName + ")"
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['turnon'] = function(block) {
  var variable = Blockly.Lua.valueToCode(block, 'VARIABLE', Blockly.Lua.ORDER_ATOMIC);
  var varName = insideChars ( variable,"'","'")
  var code = "turnOn(" + varName + ")"
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['sendheartbeat'] = function(block) {
  var code = "\n--Send Heartbeat to Server\ntmr.stop(0)\ntmr.alarm(0, 30000, tmr.ALARM_AUTO, sendHeartbeat) -- Send twice a minute\n"
  return code;
};

Blockly.Lua['extractservercommand'] = function(block) {
  var variable = Blockly.Lua.valueToCode(block, 'COMMAND', Blockly.Lua.ORDER_ATOMIC);
  var code = "extractServerCommand(" + variable + ")";
  return [code, Blockly.Lua.ORDER_NONE];
};

Blockly.Lua['extractrelaynumber'] = function(block) {
  var variable = Blockly.Lua.valueToCode(block, 'COMMAND', Blockly.Lua.ORDER_ATOMIC);
  var startIndex = Blockly.Lua.valueToCode(block, 'START', Blockly.Lua.ORDER_ATOMIC);
  
  var code = "extractRelayNumber(" + variable + "," + startIndex + ")";
  return [code, Blockly.Lua.ORDER_NONE];
};







