import time
import board
import rtc
import displayio
import os
import ssl
import fourwire
import wifi
import adafruit_requests
import adafruit_connection_manager
from adafruit_io.adafruit_io import IO_HTTP
from adafruit_st7789 import ST7789
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text import label
from adafruit_display_shapes.rect import Rect
from thermometer import Thermometer
from adafruit_spa06_003 import SPA06_003

ELE_CORR = 11.2
UPDATE_INTERVAL = 10

def c2f(c):
    return (c * 9/5) + 32

def set_clock():
    try:
        now = time.struct_time(io.receive_time(timezone))
        r = rtc.RTC()
        r.datetime = time.struct_time((now.tm_year, now.tm_mon, now.tm_mday, now.tm_hour, now.tm_min, now.tm_sec, 1, -1, -1))
    except Exception as e:
        print("Failed to set RTC: ", e)

def get_time():
    r = rtc.RTC()
    now = r.datetime
    hour = now.tm_hour
    period = "am"
    if hour > 11:
        period = "pm"
    if hour > 12:
        hour = hour - 12
    if hour == 0:
        hour = 12
    return f"{hour:01d}:{now.tm_min:02d} {period}"

def get_date():
    r = rtc.RTC()
    now = r.datetime
    return f"{now.tm_mon:1}/{now.tm_mday:2}/{now.tm_year}"
    
displayio.release_displays()
spi = board.SPI()
cs = board.D15
dc = board.D32
display_bus = fourwire.FourWire(spi, command=dc, chip_select=cs, reset=None)
display = ST7789(display_bus, rotation=180, width=135, height=240, rowstart=40, colstart=53)

aio_username = os.getenv('AIO_USERNAME')
aio_key = os.getenv('AIO_KEY')
wifi_ssid = os.getenv('CIRCUITPY_WIFI_SSID')
wifi_pw = os.getenv('CIRCUITPY_WIFI_PASSWORD')
timezone = os.getenv('TIMEZONE')

wifi.radio.connect(wifi_ssid, wifi_pw)
print("Connected as: ", wifi.radio.ipv4_address)
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
io = IO_HTTP(aio_username, aio_key, requests)

set_clock()
print(get_time(), " ", get_date())

i2c = board.STEMMA_I2C()
spa = SPA06_003.over_i2c(i2c)
time.sleep(2)

print(spa.temperature, c2f(spa.temperature), spa.pressure + ELE_CORR)

splash = displayio.Group()
display.root_group = splash

display_background = Rect(0, 0, display.width, display.height, fill=0x000088)
splash.append(display_background)

font17 = bitmap_font.load_font("/fonts/Calibri-17.pcf")
font23 = bitmap_font.load_font("/fonts/Calibri-23.pcf")

dh = display.height
tw=display.width - 40

therm = Thermometer(
    anchor=(20,5),
    display=display,
    tick_font=font17,
    frame_height=display.height - 20,
    frame_width=tw,
    temp_min=50,
    temp_max=90,
    scale_margin_top = 10,
    colors={
        "bg": 0x000088,
        "fill_apparent": 0xFF0000,
    }
)

splash.append(therm.group)

bottom_label = label.Label(font23, text=f"{c2f(spa.temperature):.1f} °F", anchored_position = (display.width//2, 220), anchor_point = (0.5, 0.0))
splash.append(bottom_label)

therm.update(int(c2f(spa.temperature)),int(c2f(spa.temperature)))
next_cycle = time.monotonic() + UPDATE_INTERVAL
time_cycle = time.monotonic() + UPDATE_INTERVAL * 400

cycle = 1
while True:
    if time.monotonic() > time_cycle:
        time_cycle = time.monotonic() + UPDATE_INTERVAL * 400
        try:
            set_clock()
        except Exception as e:
            print("Error setting time: ", e)
    if cycle == 5:
        cycle = 0
    if time.monotonic() > next_cycle:
        next_cycle = time.monotonic() + UPDATE_INTERVAL
        cycle = cycle + 1
        temp_c = None
        pressure_hpa = None
        if cycle in (3, 4, 5):
            temp_c = spa.temperature
            pressure_hpa = spa.pressure + ELE_CORR
        if cycle == 1:
            bottom_label.color = 0xFF88FF
            bottom_label.text = get_time()
        elif cycle == 2:
            bottom_label.color = 0x55FF55
            bottom_label.text = get_date()
        elif cycle == 3:
            bottom_label.color = 0xFFFFFF
            t = c2f(temp_c)
            ft = f"{t:.1f} °F"
            therm.update(t,t)
            bottom_label.text = ft
        elif cycle == 4:
            bottom_label.color = 0xFFFF00
            ft = f"{temp_c:.1f} °C"
            bottom_label.text = ft
        elif cycle == 5:
            bottom_label.color = 0x00FF00
            bottom_label.text = f"{pressure_hpa:.1f} hPa"
        else:
            pass

    time.sleep(.1)