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

LiquidCrystal_I2C lcd(0x27, 20, 4);

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

const String serverURL = "http://aa01-2001-448a-7026-37a5-7d0e-ba55-47ea-7e0d.ngrok.io/mine";

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("ARDUMEKA COIN MINER");

  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("OK! IP=");
  Serial.println(WiFi.localIP());
  
}

void loop() {

  if(WiFi.status() == WL_CONNECTED){
    HTTPClient http;
    http.begin(serverURL);

    int httpResponseCode = http.GET();
    Serial.print("Response Code: ");
    Serial.println(httpResponseCode);

    if (httpResponseCode == 200) {
      char input[500];
      String payload = http.getString();
      payload.toCharArray(input, 500);
      DynamicJsonDocument doc(JSON_OBJECT_SIZE(6));
      DeserializationError error = deserializeJson(doc, input);

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

      String Hash = doc["Hash"]; 
      int Nonce = doc["Nonce"]; 
      int Transactions = doc["Transactions"]; 
      int Balance = doc["Balance"];

      lcd.setCursor(0,1);
      lcd.print("Nonce: ");
      lcd.print(Nonce);
      lcd.print(" ");
      lcd.setCursor(0,2);
      lcd.print("Balance: ");
      lcd.print(Balance);
      lcd.print(" AMC");
      lcd.setCursor(0,3);
      lcd.print("Transactions: ");
      lcd.print(Transactions);

      Serial.println("---------ARDUMEKA COIN MINING-----------");
      Serial.print("Hash: ");
      Serial.println(Hash);
      Serial.print("Nonce: ");
      Serial.println(Nonce);
      Serial.print("Transactions: ");
      Serial.println(Transactions);
      Serial.print("Balance: ");
      Serial.print(Balance);
      Serial.println(" AMC");
      
  
      Serial.println();
    }
    else {
      Serial.print("Request Failed!");
      Serial.println(http.errorToString(httpResponseCode));
      Serial.println("");
    }
    delay(3000);
  }
  else{
    Serial.println("WiFi Disconnected");
  }
}