from time import sleep
from machine import Pin, I2C
import network
import urequests as requests
from pico_i2c_lcd import I2cLcd

sleep(0.1) # Wait for USB to become ready

print("Hello, Pi Pico!")

# CONSTANTS
WIFI_NAME = "Wokwi-GUEST"
WIFI_PASS = ""

button1 = Pin(3, Pin.IN, Pin.PULL_UP)
button2 = Pin(27, Pin.IN, Pin.PULL_UP)
led_green = Pin(1, Pin.OUT)
led_red = Pin(28, Pin.OUT)

i2c = I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)

def connectWifi():
    wlan = network.WLAN(network.STA_IF)
    print("Connecting to WIFI", end="")
    wlan.active(True)
    wlan.connect(WIFI_NAME, WIFI_PASS)
    while not wlan.isconnected():
        print(".", end="")
        sleep(1)
    print("")
    return wlan


def main():
    visiting = 0
    total = 0
    print("Program starting")
    sleep(1)
    wlan = connectWifi()
    response = requests.get("http://20.223.160.220/api/counter")
    print(response.text)
    responseInText = response.text
    #print(responseInText)
    numbers = []
    for char in responseInText:
        if char.isdigit():
            numbers.append(int(char))
    #print(numbers)
    visiting = numbers[0]
    total = numbers[1]
    #print(visiting)
    #print(total)

    while True:
        if button1.value() == 0:
            #print("Green button is pressed")
            led_green.toggle()
            visiting += 1
            total += 1
            print("People inside the area: "+ str(visiting))
            print("Total amount of visitors today: "+ str(total))
            lcd.putstr("Visiting: " + str(visiting))
            lcd.putstr("Total: " + str(total))
            requests.get("http://20.223.160.220/api/add")
            sleep(0.2)
            led_green.toggle()

        if button2.value() == 0 and visiting > 0:
            #print("Red button is pressed")
            led_red.toggle()
            visiting -= 1
            print("People inside the area: "+ str(visiting))
            print("Total amount of visitors today: "+ str(total))
            lcd.putstr("Visiting: " + str(visiting))
            lcd.putstr("Total: " + str(total))
            requests.get("http://20.223.160.220/api/reduce")
            sleep(0.2)
            led_red.toggle()
        lcd.clear()

main()