import easywifi, easydraw, urandom, gc, badge, ugfx
from time import *

easydraw.msg("Connecting to WiFi", title = 'Still Connecting Anyway...', reset = True)
easywifi.enable(True)
if easywifi.state==False:
    easydraw.msg("not connected, waiting 5secs to try again")
    badge.eink_busy_wait()
    import machine
    machine.deepsleep(5000)

easydraw.msg("Connecting to MQTT")

from umqtt.simple import MQTTClient

# Callback, received messages will go here
def mqtt_callback(topic, msg):
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  ugfx.clear(ugfx.BLACK)
  ugfx.flush()
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  ugfx.clear(ugfx.BLACK)
  ugfx.flush()
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()
  # Clear the screen a few times to prevent ghosting
  ugfx.string(0, 0, "NOTICE", "PermanentMarker22", ugfx.BLACK) 
  ugfx.string_box(0, 25, 296, 70, msg, "Roboto_Regular12", ugfx.BLACK, ugfx.justifyLeft)
  ugfx.string_box(0, 95, 296, 30, "i am listening for notices on MQTT @ " + str(topic), "Roboto_Regular12", ugfx.BLACK, ugfx.justifyCenter)
  ugfx.flush()

def main(server="mqtt.bitlair.nl"):
  owner_name = badge.nvs_get_str("owner", "name", "HELP IK HEB GEEN OWNER NAME")
  clientname = "noticeboard_" + owner_name

  topic = b"bitlair/noticeboard/" + owner_name

  client = MQTTClient(clientname, server)
  client.set_callback(mqtt_callback)
  client.connect()
  client.subscribe(topic)
  easydraw.msg("connected, subscribed to topic")
  easydraw.msg(str(topic))
  client.check_msg()
  while True:
    gc.collect()
    client.check_msg()
    sleep(1)

  client.disconnect()
  easydraw.msg("disconnected, broke out of main loop for some reason")

main()