//extern ESP8266WebServer httpServer;

static const char httpRoot[] PROGMEM =
  R"(<html><body>
  <h1><span id='devname'></span></h1>
  <h3>WiFi Switch</h3>
  <form id='BtnFrm1'><input type='hidden' name='Btn1' value='1'></form>
  <form id='BtnFrm2'><input type='hidden' name='Btn2' value='1'></form>
  <form id='BtnFrm3'><input type='hidden' name='Btn3' value='1'></form>
  <div style='font-size:xx-large'>
  <div id='sw1div'>1: <input type='button' id='tbtn1' onclick='return sendBtn(1)'/><br></div>
  <div id='sw2div' style='display:none;'>2: <input type='button' id='tbtn2' onclick='return sendBtn(2)'/><br></div>
  <div id='sw3div' style='display:none'>3: <input type='button' id='tbtn3' onclick='return sendBtn(3)'/><br></div>
  </div>
  <br>  
  <br>
  WiFi verbunden mit <i><span id='ssid'></span></i>.<br>
  <h6>Letztes Update vor
  <span id='ut'></span> Sekunden.
  <span id='status'></span>
  </h6>
  <br>
  <a href='/wifi.htm'>WiFi-Einstellungen</a><br>
  <a href='/config'>Einstellungen</a><br>
  <a href='/update'>Firmware Update</a>
  <script>
  function g(i) { return document.getElementById(i) };
  var xhttp, updateTime;
  var textA = 'AUS';
  var textE = 'EIN';
  
  function sendBtn(btn) {
  var frmn='BtnFrm'+btn;
  var form = g(frmn);
  return transmit(form);
  }
  
  function transmit(f) {
    if (!xhttp) { 
      g('status').innerHTML = 'l&auml;dt...';
      xhttp = new XMLHttpRequest();
   xhttp.timeout=2000;
      xhttp.open('POST', 'api');
      xhttp.send(f ? (new FormData(f)) : '');
      xhttp.onreadystatechange = function () {
        if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
          var data = JSON.parse(xhttp.responseText);
          g('ssid').innerHTML = data.ssid;
      if(data.devname != undefined) g('devname').innerHTML = data.devname;
   
    if(data.swState2 != undefined) g('sw2div').style.display='inline';
    else g('sw2div').style.display='none';
    if(data.swState3 != undefined) g('sw3div').style.display='inline';
    else g('sw3div').style.display='none';
      
      if(data.swState1 == '1') g('tbtn1').value = textE;
      else g('tbtn1').value = textA;
    if(data.swState2 == '1') g('tbtn2').value = textE;
      else g('tbtn2').value = textA;
    if(data.swState3 == '1') g('tbtn3').value = textE;
      else g('tbtn3').value = textA;
          xhttp = null;
          updateTime = 0;
        }
      }
    }
    return false;
  }
  transmit();
  setInterval(function () { g('ut').innerHTML = ++updateTime; }, 1000);
  setInterval(transmit, 5000);
</script>
  </body></html>)";


static const char httpConfPage[] PROGMEM = 
R"(<html><body>
  <h1>WiFi Thermostat</h1>
  <h2>Configuration</h2>
  <a href='/'>Home</a>
  </body></html>)";

void httpServerHandleRoot() {
  httpServer.send_P(200, "text/html", httpRoot);
}

void httpServerHandleConfPage() {
  httpServer.send_P(200, "text/html", httpConfPage);
}

void httpServerHandleNotFound() {
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += httpServer.uri();
  message += "\nMethod: ";
  message += (httpServer.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += httpServer.args();
  message += "\n";
  for (uint8_t i = 0; i < httpServer.args(); i++) {
    message += " " + httpServer.argName(i) + ": " + httpServer.arg(i) + "\n";
  }
  httpServer.send(404, "text/plain", message);
}


void httpServerInit() {
  //handles commands from webpage, sends live data in JSON format
  httpServer.on("/api", []() {
    //Serial.print("httpServer.on /api");
    if (httpServer.hasArg("Btn1")) {
      lastSwitchSource[0] = 2;
      relaisToggle(0);
      Serial.println("web Btn1");
    } //if
    if (httpServer.hasArg("Btn2")) {
      lastSwitchSource[1] = 2;
      relaisToggle(1);
      Serial.println("web Btn2");
    } //if
    if (httpServer.hasArg("Btn3")) {
      lastSwitchSource[2] = 2;
      relaisToggle(2);
      Serial.println("web Btn3");
    } //if

    //build json object of program data
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject &json = jsonBuffer.createObject();
    json["ssid"] = WiFi.SSID();
    json["swState1"] = relais_state[0];
    if(RELAIS_COUNT > 1) json["swState2"] = relais_state[1];
    if(RELAIS_COUNT > 2) json["swState3"] = relais_state[2];
    json["devname"] = deviceName;
    
    char jsonchar[200];
    json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
    httpServer.send(200, "application/json", jsonchar);

  }); //httpServer.on /api

  //get heap status, analog input value and all GPIO statuses in one json call
  httpServer.on("/info", HTTP_GET, []() {
    String json = "{";
    json += "\"wifissid\":\"" + WiFi.SSID() + "\"";
    json += "\"heap\":" + String(ESP.getFreeHeap());
    //json += ", \"analog\":" + String(analogRead(A0));
    //json += ", \"gpio\":" + String((uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)));
    json += "}";
    httpServer.send(200, "text/json", json);
    json = String();
  }); //httpServer.on /info

  httpServer.on("/", []() {
    httpServerHandleRoot();
  });

  httpServer.on("/config", []() {
    httpServerHandleConfPage();
  });

  httpServer.onNotFound([]() {
    httpServerHandleNotFound();
  }); //httpServer.onNotFound

  // HTTP Updater at /update
  httpUpdater.setup(&httpServer);


  httpServer.begin();
}


