#include <WiFi.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);

byte tempicon[] = {
  0x04,0x0A,0x0A,0x0E,0x0E,0x1F,0x1F,0x0E
};
byte humidicon[] = {
  0x04,0x04,0x0A,0x0A,0x11,0x11,0x11,0x0E
};


#include "weatherFetcher.h"

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

void setup() {
  Serial.begin(115200);
  delay(100);

  lcd.init();
  lcd.createChar(0, tempicon);
  lcd.createChar(1, humidicon);
  lcd.backlight();

  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);

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

  Serial.println("Connected to WiFi");

  initWeather();
  xTaskCreatePinnedToCore(
    fetchWeather,
    "fetchWeather",     /* name of task. */
    10000,       /* Stack size of task */
    NULL,        /* parameter of the task */
    1,           /* priority of the task */
    &handleWeather,      /* Task handle to keep track of created task */
    0);
  Serial.print("Fetching data");
  while (!currentWeather.isInit) {
    Serial.print(".");
    delay(250);
  }
  displayWeatherInfo(currentWeather.temp2m, currentWeather.humid2m, currentWeather.weather_desc);
}

void loop() {
  // Nothing to do here
  if (Serial.available() > 0) {
    String inp = Serial.readString();
    inp.trim();
    if (inp == "r") {
      // check whether the weather fetching task is running or not
      int state = eTaskGetState(handleWeather); // 1 for ready; 0 for running
      if (state == 0) Serial.println("Running");
      else {
        initWeather();
        xTaskCreatePinnedToCore(
          fetchWeather,
          "fetchWeather",     /* name of task. */
          10000,       /* Stack size of task */
          NULL,        /* parameter of the task */
          1,           /* priority of the task */
          &handleWeather,      /* Task handle to keep track of created task */
          0);
        while (!currentWeather.isInit) {
          Serial.print(".");
          delay(250);
        }
        displayWeatherInfo(currentWeather.temp2m, currentWeather.humid2m, currentWeather.weather_desc);
      }
    }
  }
}