import time
import network
import urequests as requests

from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd

I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #initializing the I2C method for ESP32
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.putstr("Hello")

ssid = 'wokwi-GUEST'
password = ''
print("Connecting to wifi", end ="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(ssid, password)
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print("connected!")

my_id = "2cfea83a122baaa50ca3f7b0fa4b3b11"
my_city = "HaNoi"
my_url = f"https://api.openweathermap.org/data/2.5/weather?q=Hanoi&appid={my_id}"
api_url = "https://timeapi.io/api/time/current/zone?timeZone=Asia%2FHoChiMinh"

while True:
  response = requests.get(url=api_url).json()
  hour = response ['hour']
  minute = response ['minute']
  lcd.move_to(0, 0)
  lcd.putstr(f"{my_city}, {hour}:{minute}")

  if(minute % 30 == 0):
    res = requests.get(url=my_url).json()
    print("Current weather: ", res['weather'][0]["description"])

    temperature = res['main']['temp']
    humidity = res['main']['humidity']
    lcd.move_to(0,1)
    lcd.putstr(f"T: {temperature}, H: {humidity}")
time.sleep(10)