import ugfx
import wifi
import socket
import time
import badge
import machine
 
ugfx.init ()
ugfx.input_init ()
wifi.init ()
badge.leds_init ()
badge.leds_enable ()

reset_pressed = False

def on_pressed (pressed):
  global reset_pressed
  reset_pressed = True

def go_home (pressed):
  machine.deepsleep (1)

ugfx.input_attach (ugfx.BTN_B, go_home)
ugfx.input_attach (ugfx.BTN_A, on_pressed)
  
for i in range (0, 3):
  ugfx.clear (ugfx.BLACK)
  ugfx.flush ()
  ugfx.clear (ugfx.WHITE)
  ugfx.flush ()
ugfx.line (2, 2, 294, 2, ugfx.BLACK)
ugfx.line (2, 3, 294, 3, ugfx.BLACK)
ugfx.line (2, 2, 2, 126, ugfx.BLACK)
ugfx.line (3, 2, 3, 126, ugfx.BLACK)
ugfx.line (2, 126, 294, 126, ugfx.BLACK)
ugfx.line (2, 125, 294, 125, ugfx.BLACK)
ugfx.line (294, 2, 294, 126, ugfx.BLACK)
ugfx.line (295, 2, 295, 125, ugfx.BLACK)
ugfx.circle (12, 12, 4, 2)
ugfx.circle (284, 12, 4, 2)
ugfx.string (105, 20, "SECONDS ", "Roboto_BlackItalic24", ugfx.BLACK)
ugfx.string (52, 48, "SINCE SOMEONE ", "Roboto_BlackItalic24", ugfx.BLACK)
ugfx.string (52, 76, "RESET THIS SIGN ", "Roboto_BlackItalic24", ugfx.BLACK)
ugfx.string (12, 112, "A: Reset ", "Roboto_Regular12", ugfx.BLACK)
ugfx.string (210, 112, "xkcd.com/363", "Roboto_Regular12", ugfx.BLACK)
ugfx.flush ()

time_reset = time.time ()

while True:
  time.sleep_ms (750)
  time_now = time.time ()
  do_reset = reset_pressed  
  reset_pressed = False
  if (do_reset):
    time_reset = time_now
  ugfx.area (120, 112, 60, 12, ugfx.WHITE)
  if wifi.sta_if.isconnected ():
    try:
      ai = socket.getaddrinfo ("sign.sytes.net", 80)
      addr = ai [0] [-1]
      s = socket.socket ()
      s.connect (addr)
      if (do_reset):
        s.write (b"GET /sign.php?reset HTTP/1.0\r\n\r\n")
      else:
        s.write (b"GET /sign.php HTTP/1.0\r\n\r\n")
      response = s.read ()
      s.close ()
      response_string = response.decode ("utf-8")
      seconds_since_reset = int (response_string.split ("\r\n\r\n") [-1])
      ugfx.string (120, 112, "WiFi OK  ", "Roboto_Regular12", ugfx.BLACK)
    except:
      seconds_since_reset = time_now - time_reset    
      ugfx.string (120, 112, "Con Error", "Roboto_Regular12", ugfx.BLACK)
  else:
    seconds_since_reset = time_now - time_reset    
    ugfx.string (120, 112, "WiFi NOK ", "Roboto_Regular12", ugfx.BLACK)      
    wifi.init ()
  seconds_since_reset %= 10000
  ugfx.area (42, 20, 62, 24, ugfx.WHITE)
  ugfx.string_box (42, 20, 62, 24, str (seconds_since_reset), "Roboto_BlackItalic24", ugfx.BLACK, ugfx.justifyRight)
  ugfx.flush ()
  led = seconds_since_reset >> 6
  led %= 4
  seconds_since_reset %= 64
  led_data = [0] * 24
  for i in range (0, 6):
    if (((seconds_since_reset >> i) & 1) > 0):
      led_data [(i*4)+led] = 8
  badge.leds_send_data (bytes (led_data))