#include "SerialWombat.h"
#include "SerialWombat18ABVGADriver.h"  // If this line throws an error, get SerialWombat18ABVGADriver library though the library manager
/*
This example shows how to configure pins 14-18 of the Serial Wombat 18AB chip to output VGA,
and display different colored text on different lines using text generated by the 
AdafruitGFX library, the SerialWombat18ABVGA pin mode, and the SerialWombat18ABVGADriver
wrapper to provide AdaFruitGFX compatible interfaces.

We will display the words Red, Blue, Green, Cyan, Magenta, Yellow and White in their colors.

Note that colors need to be set for an entire line of pixels, and that color handling is done
through the Serial Wombat 18AB Pin mode, not the color functions of the AdafruitGFX display.
You can almost think of it as putting a tinted color transparency over the screen at the 
driver layer.  Any of you kids ever play VecTrex?  

Serial Wombat 18AB Firmware 2.1 or later is needed to use this example.

This example assumes a Serial Wombat 18AB chip is attached to the Arduino board via I2C.
In this case we're assuming an ESP-01 module with I2C Data and Clock lines on ESP-02 pins 2 and 0.

Connections:
VGA VSYNC (VGA Pin 14) -> 100 ohm Resistor -> SW Pin 18
VGA HSYNC (VGA Pin 13) -> 100 ohm Resistor ->SW Pin 17
VGA Red   (VGA Pin 1) -> 280 ohm Resistor -> SW Pin 16
VGA Green (VGA Pin 2) -> 280 ohm Resistor -> SW Pin 15
VGA Blue (VGA Pin 3) -> 280 ohm Resistor -> SW Pin 14

A video demonstrating the use of the VGA pin mode on the Serial Wombat 18AB chip is available at:
TODO

Documentation for the VGA class is available at:
https://broadwellconsultinginc.github.io/SerialWombatArdLib/class_serial_wombat18_a_b_v_g_a.html

*/
#include <WiFi.h>

const char* ssid     = "BILLBOARD";
const char* password = "123456789";

// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;

SerialWombatChip sw;
SerialWombat18ABVGA vgaDriver(sw);
SerialWombat18ABVGADriver vgaDisplay(vgaDriver);
IPAddress IP;

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(115200);
  delay(500);

  uint8_t i2cAddress = sw.find();
  if (i2cAddress == 0) {
    showNotFoundError(); // see showErrorNotFound tab
  }
  sw.begin(Wire, i2cAddress);
  sw.queryVersion();
  Serial.print("Version "); Serial.println((char*)sw.fwVersion);
  versionCheck(); //see showErrorNotFound tab
  Serial.println("SW18AB Found.");

// Connect to Wi-Fi network with SSID and password
  Serial.print("Setting AP (Access Point)");
  // Remove the password parameter, if you want the AP (Access Point) to be open
  WiFi.softAP(ssid, password);

   IP = WiFi.softAPIP();
    server.begin();
  vgaDriver.begin(18, 0x0000);

  showGraphicAndText();
}

void loop() {
  // put your main code here, to run repeatedly:
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
       // Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            int index = 0;
            
            index = header.indexOf("=");
            Serial.println ("++++++++++++++++++++++++++++++++++++++++++++++");
            Serial.println(header);
            Serial.println ("++++++++++++++++++++++++++++++++++++++++++++++");
            Serial.print("="); Serial.println(index);
            int endOfFirstLine = header.indexOf("\n");
            if(index >= 0 && index < endOfFirstLine)
            {
            vgaDisplay.fillScreen(0);
            vgaDisplay.setCursor(0, 0);
            }
            while (index >= 0 && index < endOfFirstLine)
            {
              int end = header.indexOf("&",index + 1);
              Serial.print("&"); Serial.println(end);
              if (end == -1 || end > endOfFirstLine)
              {
                end = header.indexOf(" HTTP", index);
                if (end == -1)
                {
                  end = index + 1;
                }
                Serial.print(" HTTP "); Serial.println(end);
              }
              
              String s = header.substring(index + 1,end);
              s.replace("+"," ");
              Serial.println(s);
              vgaDisplay.println(s);
              index = header.indexOf("=",end);
              Serial.print("="); Serial.println(index);
              
            }
            
            
            // Display the HTML web page
            client.println(R"JFIE(
            <!DOCTYPE html><html>
            <head><meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="icon" href="data:,">
            <style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
            .button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;
            text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
            .button2 {background-color: #555555;}</style></head> )JFIE");
            
            // Web Page Heading
            client.println("<body><h1>VGA Billboard</h1>");
          
            client.println(R"JFIE(
            <form action="/action_page.php">
  <input type="text" id="fname" name="L0" value="Serial Wombat"><br><br>
  <input type="text" id="lname" name="L1" value="18AB VGA"><br><br>
  <input type="text" id="lname" name="L2" value="BillBoard"><br><br>
  <input type="text" id="lname" name="L3" value="Demo"><br><br>
  <input type="text" id="lname" name="L4" value="Broadwell"><br><br>
  <input type="text" id="lname" name="L5" value="Consulting"><br><br>
  <input type="text" id="lname" name="L6" value="Inc."><br><br>
  <input type="submit" value="Submit">
</form> )JFIE");
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}



#define LINEHEIGHT 8  // Based on the size of the font
void showGraphicAndText()
{
  vgaDisplay.fillScreen(0);
  vgaDisplay.setCursor(0, 0);
  vgaDisplay.setTextSize(2);


  vgaDisplay.println(IP);

  vgaDriver.setLineColor(4, 0, LINEHEIGHT * 2);  // 4 = Red
  vgaDriver.setLineColor(2, LINEHEIGHT * 2, LINEHEIGHT * 4);  // 2 = Green
  vgaDriver.setLineColor(1, LINEHEIGHT * 4, LINEHEIGHT * 6);  // 1 = Blue
  vgaDriver.setLineColor(3, LINEHEIGHT * 6, LINEHEIGHT * 8);  // 3 = Cyan
  vgaDriver.setLineColor(5, LINEHEIGHT * 8, LINEHEIGHT * 10);  // 5 = Magenta
  vgaDriver.setLineColor(6, LINEHEIGHT * 10, LINEHEIGHT * 12); // 6 = Yellow
  vgaDriver.setLineColor(7, LINEHEIGHT * 12, LINEHEIGHT * 14); // 7 = White
}
