#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);

const char* ssid = "Wokwi-GUEST";
const char* password = "";

const String url = "https://saklar-cerdas-demo.glitch.me/info/v2";

int LED[] = {2, 4, 5, 18};
String lastResult;

uint8_t emptyI[8] = {
  0b11111, //
  0b00000, //
  0b00000, //
  0b00000, //
  0b00000, //
  0b00000, //
  0b00000, //
  0b11111, //
};
uint8_t emptyLI[8] = {
  0b11111, //
  0b10000, //
  0b10000, //
  0b10000, //
  0b10000, //
  0b10000, //
  0b10000, //
  0b11111, //
};
uint8_t emptyRI[8] = {
  0b11111, //
  0b00001, //
  0b00001, //
  0b00001, //
  0b00001, //
  0b00001, //
  0b00001, //
  0b11111, //
};
uint8_t fullI[8] = {
  0b11111, //
  0b11111, //
  0b11111, //
  0b11111, //
  0b11111, //
  0b11111, //
  0b11111, //
  0b11111, //
};

void updateData() {
  
  HTTPClient http;
  http.useHTTP10(true);
  http.begin(url);
  http.GET();
  String result = http.getString();
  if(result == lastResult) return; 
  else lastResult = result;

  DynamicJsonDocument doc(2048);
  DeserializationError error = deserializeJson(doc, result);

  // Test if parsing
  if (error) {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
  }

  String l0 = doc["0"].as<String>();
  String l1 = doc["1"].as<String>();
  String l2 = doc["2"].as<String>();
  String l3 = doc["3"].as<String>();
  String lastDate = doc["inDate"].as<String>();
  String lastTime = doc["inTime"].as<String>();
  http.end();
  
  for(int n : LED){
    digitalWrite(n, LOW);
  }

  LCD.clear();
  LCD.setCursor(0, 0);
  LCD.println(lastTime + " UTC+00");
  LCD.setCursor(1, 1);
  LCD.println("\x04\x03\x03\x05");
  if(l0 == "1") {
    LCD.setCursor(1, 1);
    LCD.println("\x06");
    digitalWrite(LED[0], HIGH);
  }
  if(l1 == "1") {
    digitalWrite(LED[1], HIGH);
    LCD.setCursor(2, 1);
    LCD.println("\x06");
  }
  if(l2 == "1") {
    digitalWrite(LED[2], HIGH);
    LCD.setCursor(3, 1);
    LCD.println("\x06");
  }
  if(l3 == "1") {
     digitalWrite(LED[3], HIGH);
    LCD.setCursor(4, 1);
    LCD.println("\x06");
  }
}

void setup() {
  for(int n : LED){
    pinMode(n, OUTPUT);
  }

  WiFi.begin(ssid, password, 6);
  Serial.begin(9600);
  
  LCD.createChar(3, emptyI);
  LCD.createChar(4, emptyLI);
  LCD.createChar(5, emptyRI);
  LCD.createChar(6, fullI);
  LCD.init();
  LCD.backlight();
  LCD.begin(16, 2);
  LCD.setCursor(0, 0);
  LCD.print("Connecting to ");
  LCD.setCursor(0, 1);
  LCD.print("WiFi ");

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  
  LCD.clear();
  LCD.setCursor(0, 0);
  LCD.println("Connected");
  LCD.setCursor(0, 1);
  LCD.println("Updating data...");

  updateData();
}

void loop() {
  while (WiFi.status() == WL_CONNECTED) {
    updateData();
    delay(100);
  }
}