import urequests as requests
import appglue
import wifi
import time
import badge
import easydraw
import ugfx

badge.init()
ugfx.init()
wifi.init()
badge.leds_init()
badge.vibrator_init()

ugfx.clear(ugfx.BLACK)
ugfx.flush()
ugfx.clear(ugfx.WHITE)
ugfx.flush()



def set_message(text):
  ugfx.clear(ugfx.BLACK)
  ugfx.clear(ugfx.WHITE)
  ugfx.string(10,60,text,"Roboto_Regular12", 0)
  ugfx.flush()
  badge.eink_busy_wait()
    
def home(pressed):
  if pressed:
    appglue.home()

def vendmate(pressed):
  if pressed:
    try:
      led_array = bytes([255, 0, 0, 100, 255, 0, 0, 100, 255, 0, 0, 100, 255, 0, 0, 100, 255, 0, 0, 100, 255, 0, 0, 100])
      badge.leds_enable()
      badge.leds_send_data(led_array,24)
      time.sleep(1)
      badge.leds_disable()
      badge.vibrator_activate(0xFF)
      set_message("U WOT MATE?!?!")
      url = "https://automate.nwlab.nl/api/vend"
      h = {"Authorization":"Basic YmFkZ2U6NjViY2Q0YWRhZjhiMzBjNjU3Y2QwYjUyZmFlMzE1NzY="}
      data = requests.get(url, headers=h)
      data.close()
      ugfx.string(5,70,"Look at the","Roboto_Regular12",ugfx.BLACK)
      ugfx.string(5,90,"vending machine","Roboto_Regular12",ugfx.BLACK)
    except Exception as e:
      set_message("Unexpected error: "+str(e))
      time.sleep(5)
      appglue.home()

def main():
    ugfx.clear(ugfx.WHITE)
    ugfx.string(5,50,"Free Mate @ Mozart","Roboto_Regular12",ugfx.BLACK)
    ugfx.string(5,70,"When u get there","Roboto_Regular12",ugfx.BLACK)
    ugfx.string(5,90,"press A!","Roboto_Regular12",ugfx.BLACK)
    ugfx.flush()

wifi.connect()
if not wifi.wait(30, True):
    easydraw.msg("Nope, no Wi-Fi")
    time.sleep(2)
    appglue.home()
    
ugfx.input_init()
ugfx.input_attach(ugfx.BTN_A, vendmate)
ugfx.input_attach(ugfx.BTN_SELECT, home)
main()