 #include <WiFi.h>
#include <ESP32WebServer.h>
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// jfs Wemos lolin32
// jfs Heltec WiFi kit 32 (weisses Board)
// #define HELTEC

ESP32WebServer server(80);

// Initialize the OLED display using Wire library
#ifdef HELTEC
SSD1306  display(0x3c, 4, 15);
#else

SSD1306  display(0x3c, 5, 4);
#endif

//SSD1306  display(0x3c, 5, 4);  //vorher 5,4 für wemos | Heltec WiFi Kit 32 4,15

const int mxSize=4;
String ssids[mxSize] ={"GAST","pipanet","FRITZ!Box Gastzugang","WLAN-DE8245"};
String ssidp[mxSize] = {"passatvr6","passatvr6","praxis123","4955065570896956"};
boolean conok =false;

void netfound(int i){
     display.clear();
     display.setColor(BLACK);
     display.fillRect(0, 0, 128, 10);
     display.setColor(WHITE);
     display.drawString(0,0,String(i));
     display.drawString(20,0,"networks found");
     display.display(); 
}

boolean init_wifi(){
    boolean ok = false;
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);
    int n = WiFi.scanNetworks();
    Serial.println("scan done");
    if (n == 0) {
        Serial.println("no networks found");
        netfound(0);
    } else {
        Serial.print(n);
        Serial.println(" networks found");
        netfound(n);        
        for (int i = 0; i < n; ++i) {
            // Print SSID and RSSI for each network found
            //Serial.print(i + 1);
            //Serial.print(": ");
            //Serial.print(WiFi.SSID(i));
            for (int p=0;p<mxSize;p++){
              if (WiFi.SSID(i).equals(ssids[p])){
                //Serial.print(i);
                //Serial.print("-");
                //Serial.print(p);
                String pp = ssidp[p];
                String ss = WiFi.SSID(i);
                //Serial.print(ss);
                //Serial.print(" ");
                //Serial.println(pp);
                WiFi.begin(ss.c_str(), pp.c_str());
                i=n;
                ok = true;
                //Serial.print(WiFi.status());
              }
            }
            //Serial.print(" (");
            //Serial.print(WiFi.RSSI(i));
            //Serial.print(")");
            //Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
            delay(10);
        }
    }     
    return ok;
}

void setup() {
  //für Wiufi Kit 32
#ifdef HELTEC
  pinMode(16,OUTPUT); digitalWrite(16, LOW); delay(50); digitalWrite(16, HIGH);
#endif 
  Serial.begin(115200); 
  display.init();
  display.flipScreenVertically();
  display.clear();
  display.drawString(0, 0, "Starting...");
  display.display();
  while (!init_wifi()){
    delay(200);  
  }
  display.drawString(0, 10, "Connecting to WiFi...");
  display.display();
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  display.drawString(0, 20, "\nWiFi connected, IP address: "); 
  display.drawString(0, 30, WiFi.localIP().toString());
  display.display();


  server.onNotFound(handleNotFound);
  server.on("/", menu);
  server.on("/print", sendToPrinter);
  
  
  server.begin();
  display.drawString(0, 40, "HTTP started on port 80");
  display.display();
}



void loop() {
  // deals with the Wifi clients and responds, calls the callbacks, etc. ...
  server.handleClient();
  delay(1);
}



void menu() {
  Serial.println("Menu...");
  String message = "<h1>Thermal Printer</h1>";
  message += "<form action=\"/print\" id=\"frm\"><input type=\"submit\" value=\"Send to printer\"  style=\"height:200px;width:200px\"> </form>";
  message += "<textarea rows=\"10\" cols=\"50\" name=\"text\" form=\"frm\"> Enter text here...</textarea>";
  server.send(200, "text/html", message);
}

void sendToPrinter() {
  // we expect one and only 1 var which is the text to print
  String var = server.argName(0);
  String value = server.arg(0);


  if (var == "text") {
    Serial.print("Received to print: "); Serial.println(value);
    //serialPrinter.println(value);
    cutPaper();
    
  } 
  else Serial.println("UNKNOWN var " + var );

  menu();
}


void cutPaper() {
  //extra empty rows to cut below the latest text
  //serialPrinter.println("\n\n\n");
  byte cutCmd[] = {0x1B, 0x69, 0x0A};
  //serialPrinter.write(cutCmd, sizeof(cutCmd));
}

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