import time, ntp, wifi, system, machine
import ugfx, easydraw


if not ntp.local_time_available():
    if not wifi.status():
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()
        easydraw.messageCentered('Connecting to WiFi')
        wifi.connect()
        if not wifi.wait():
            print('No wifi')
            ugfx.clear(ugfx.WHITE)
            ugfx.flush()
            easydraw.messageCentered('Couldn\'t connect to WiFi')
            time.sleep(2)
            print("Error connecting to wifi")
            system.reboot()

    if not ntp.set_NTP_time():
        print("Error setting time")
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()
        easydraw.messageCentered('Couldn\'t set NTP time')
        time.sleep(2)
        system.reboot()

	wifi.disconnect()

## Taken from Bas' PrettyClock.
## Get your timezone from
## https://remotemonitoringsystems.ca/time-zone-abbreviations.php
rtc=machine.RTC()
timezone = machine.nvs_getstr('system', 'timezone')
if timezone is None:
    timezone = 'CET-1CEST-2,M3.5.0/02:00:00,M10.5.0/03:00:00'
machine.RTC().timezone(timezone)

time_old = 0

while True:
    format_time = '%02d : %02d' % (rtc.now()[3], rtc.now()[4])
    if format_time != time_old:
        ugfx.clear(ugfx.WHITE)
        ugfx.flush()
        easydraw.messageCentered(format_time)
        time_old = format_time
    time.sleep(0.2)
system.reboot()