from machine import Pin, I2C
import time
import urequests
import network
import json
from ssd1306 import SSD1306_I2C
import framebuf, sys
import utime

#Constants
BASE_URL = "http://4.210.123.248:3000/"
PASSWORD = {"username": "iotcalc", "password": "secret"}
WLAN_ADDRESS = "Wokwi-GUEST"

INCREMENT = BASE_URL + "increment"
DECREMENT = BASE_URL + "decrement"
RESET = BASE_URL + "reset"

current = "currentVisitors"
total = "totalVisitors"

#Button configuration
plus_button = Pin(2, Pin.IN, Pin.PULL_UP) 
reset_button = Pin(3, Pin.IN, Pin.PULL_UP)
minus_button = Pin(4, Pin.IN, Pin.PULL_UP)

#Screen configuration
resolution_x = 128
resolution_y = 64
i2c_dev = I2C(1, scl=Pin(27), sda=Pin(26), freq=500)
oled = SSD1306_I2C(resolution_x, resolution_y, i2c_dev)

#Connect to wifi
def connectWifi():
    print("Connecting to Wifi", end="")
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WLAN_ADDRESS, "")

    tries = 0
    while not wlan.isconnected() and tries < 120:
        print(".", end="")
        time.sleep(1)
        tries += 1

    if wlan.isconnected():
        print(" Wifi connected.")

    elif not wlan.isconnected():
        print(" Wifi not connected, restart simulation!")
        sys.exit()

#Empty screen and add text
def screen_text(oled, count, countMax):
    oled.fill(0)
    oled.text(f"Visitors now:", 0, 5)
    oled.text(f"{count}", 0, 20)
    oled.text("Visitors today:", 0, 35)
    oled.text(f"{countMax}", 0, 50)
    oled.show()

# Add visitor
def plus():
  try:
    response = urequests.post(INCREMENT, json=PASSWORD).json()
    count = str(response[current])
    countMax = str(response[total])
    screen_text(oled, count, countMax)
    print(f"\nAdded 1\nVisitors now: {response[current]}\nVisitors today: {response[total]}")
  except Exception:
    print("\nAdding failed!")

# Remove visitor
def minus():
  try:
    response = urequests.post(DECREMENT, json=PASSWORD).json()
    count = str(response[current])
    countMax = str(response[total])
    screen_text(oled, count, countMax)
    print(f"\nRemoved 1\nVisitors now: {response[current]}\nVisitors today: {response[total]}")
  except Exception:
    print("\nRemove failed!")

# Reset visitors
def reset():
  try:
    response = urequests.post(RESET, json=PASSWORD).json()
    count = str(response[current])
    countMax = str(response[total])
    screen_text(oled, count, countMax)
    print(f"\nReset succeeded!\nVisitors now: {response[current]}\nVisitors today: {response[total]}")
  except Exception:
    print("\nReset failed!")

def main():
    connectWifi()

    #Get request for visitorcounts.
    response = urequests.get(BASE_URL).json()
    count = str(response[current])
    countMax = str(response[total])
    print(f"\nVisitors now: {response[current]}\
    \nVisitors today: {response[total]}\n")

    #Text to screen
    screen_text(oled, count, countMax)

    #Check if button on hold
    hold = False

    # Check for pressed buttons
    while True:
        if plus_button.value() == 0 and reset_button.value() == 1 and minus_button.value() == 1 and not hold:
            plus()
            hold = True

        elif minus_button.value() == 0 and reset_button.value() == 1 and plus_button.value() == 1 and not hold:
            minus()
            hold = True

        elif reset_button.value() == 0 and plus_button.value() == 1 and minus_button.value() == 1 and not hold:
            reset()
            hold = True
        
        elif plus_button.value() == 1 and minus_button.value() == 1 and reset_button.value() == 1:
            hold = False

main()