/*Follwing is a Web_Interrupt Code to Control a Surveillance Feed of a Security Server*/
#include "WizFi360.h"

// setup according to the device you use
#define WIZFI360_EVB_PICO

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"


#if defined(WIZFI360_EVB_PICO)
SoftwareSerial Serial2(6, 7); // RX, TX
HardwareSerial Serial3(1, 2); //hardware
#endif


/* Baudrate */

#define SERIAL1_BAUDRATE  115200
#if defined(WIZFI360_EVB_PICO)
#define SERIAL2_BAUDRATE  115200
#endif

/* Wi-Fi info */
char ssid[] = "********";       // your network SSID (name)
char pass[] = "********";   // your network password

int status = WL_IDLE_STATUS;  // the Wifi radio's status
String Surv_status = "off";
String Sec_status = "At Risk";
bool Save_img = false;
String img = "Save";
String Int_on = "Cam_On";
String Int_off = "Cam_off";
String Int_save = "Cam_save";
int ledStatus = LOW;

WiFiServer server(80);

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  
  // initialize serial for debugging
  Serial.begin(SERIAL_BAUDRATE);
  // initialize serial for WizFi360 module

#if defined(WIZFI360_EVB_PICO)
  Serial2.begin(SERIAL2_BAUDRATE);
#endif
  // initialize WizFi360 module

#if defined(WIZFI360_EVB_PICO)
  WiFi.init(&Serial2);
#endif

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  // start the web server on port 80
  server.begin();
}

void loop() {
  WiFiClient client = server.available();  
  if (client) {                               
    Serial.println("New client");             
    buf.init();                               
    while (client.connected()) {              
      if (client.available()) {               
        char c = client.read();               
        buf.push(c);                          

        // printing the stream to the serial monitor will slow down
        // the receiving of data from the WizFi360 filling the serial buffer
        //Serial.write(c);

        // you got two newline characters in a row
        // that's the end of the HTTP request, so send a response
        if (buf.endsWith("\r\n\r\n")) {
          sendHttpResponse(client);
          break;
        }

        
        if (buf.endsWith("GET /on")) {
          Serial.println("Turn led ON");
          ledStatus = HIGH;
          digitalWrite(LED_BUILTIN, HIGH);   
        }
        else if (buf.endsWith("GET /off")) {
          Serial.println("Turn led OFF");
          ledStatus = LOW;
          digitalWrite(LED_BUILTIN, LOW);    
        }
      }
    }

    client.stop();
    Serial.println("Client disconnected");
  }
}

void sendHttpResponse(WiFiClient client) {
  
  if (digitalRead(LED_BUILTIN) == 1)
  {
    Surv_status = "on";
    Sec_status = "Safe";
    server.on("/cam", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", Int_on.c_str());
  }
  else
  {
    Surv_status = "off";
    Sec_status = "At Risk";
    server.on("/cam", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", Int_off.c_str());
  }
  if(Surv_status == "on"&&Save_image==1){
    server.on("/cam", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", img.c_str());
    Save_image = false;
  }
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();

client.println("<!DOCTYPE html><html>");
  client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
  client.println("<link rel=\"icon\" href=\"data:,\">");
  // CSS to style the on/off buttons
  // Feel free to change the background-color and font-size attributes to fit your preferences
  client.println("<style>* {margin: 0; padding: 0; box-sizing: border-box;}");
  client.println(".button { margin-top: 10px; padding: 10px 100px; background-color: rgba(3, 237, 15, 0.852); border: none; ");
  client.println("border-radius: 10px; font-weight: 700; font-size: 1rem; cursor: pointer;}");
  client.println(".container { margin-top: 20vh; text-align: center;}");
  client.println(".status { font-size: large; margin-bottom: 20px;}");
  client.println(".heading { background-color: rgba(3, 237, 15, 0.852); color: black; text-align: center; padding: 10px;}");
  client.println(".title { font-size: 2.5rem; margin-bottom: 60px;}</style></head>");
//  client.println(".button2 {background-color: #555555;}");
    
  // Web Page Heading
  client.println("<body><header class=\"heading\"><h1>Security Server</h1></header>");
  
  // Display current state, and ON/OFF buttons
  client.println("<div class=\"container\"> <h1 class=\"title\">WizFi360 EVB PICO</h1>"); 
  client.println("<p class=\"status\">Surveillance Status " + Surv_status + "</p>");
  client.println("<p class=\"status\">Security Status is " + Sec_status + "</p>");
  // If the LED is off, it displays the ON button
  if (Surv_status == "off") {
    client.println("<p><a href=\"/on\"><button class=\"button\">Turn ON Video Cam</button></a></p>");
  } else {
    client.println("<p><a href=\"/off\"><button class=\"button\">Turn OFF Video Cam</button></a></p>");
    client.println("<p><a href=\"/on\"><button class=\"button\">SAVE an image</button></a></p>");
  }

  client.println("</div></body></html>");

  // The HTTP response ends with another blank line:
  client.println();
}

void printWifiStatus() {
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  Serial.print("SSID done ");

  // print your WiFi shield's IP address
  IPAddress ip = (192,168,1,1);
   //IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}
