import sys
import time
from hashlib import sha1
import gc
import system

import ubinascii
import network
import wifi
import display
import buttons
import audio

from umqtt.simple import MQTTClient

import mch22
import nvs
import machine
import neopixel

# catch everything and print error on display
try:

    def connectToWifi():

        display.drawFill(display.WHITE)
        display.drawText(30, 40, "Connecting to wifi...", 0x000001, "PermanentMarker22")
        display.flush()

        tries = 0

        wifi.connect()
        while not wifi.status():
            print(f'tries: {tries}')
            tries+=1

            time.sleep(0.2)
            if wifi.wait():
                time.sleep(0.2)
                print("Connected!")
                break
            else:
                display.drawFill(display.WHITE)
                display.drawText(30, 40, "No Wifi No Winks!", 0x000000, "PermanentMarker22")
                display.drawText(30, 100, f'Connecting { str(tries) } again...', 0x000000, "PermanentMarker22")
                display.flush()
            time.sleep(0.2)


    class LaserPongScoreboard:
        def drawscore(self):
            display.drawFill(display.BLACK)
            display.drawText(30, 100, self.p1score, display.WHITE, self.font, 5, 5)
            display.drawText(160+30, 100, self.p2score, display.WHITE, self.font, 5, 5)
            display.flush()
    
        def sub_cb(self,topic
        ,msg):
            print (f'received mqtt message topic: { topic }, payload: { msg }')
            if topic.endswith('/player1/score'):
                self.p1score = msg.decode("utf-8")
                self.drawscore()
            if topic.endswith('/player2/score'):
                self.p2score = msg.decode("utf-8")
                self.drawscore()
            if topic.endswith('/sound'):
                if msg.decode("utf-8") == "HIT":
                    audio.play("%s/%s" % (APP_PATH, "hit.mp3"), volume=180)
                if msg.decode("utf-8") == "MISS":
                    audio.play("%s/%s" % (APP_PATH, "miss.mp3"), volume=180)

        def __init__(self, font="roboto_regular12",server='mqtt.devlol.org',topics=['devlol/h19/mainroom/laserpong/player1/score','devlol/h19/mainroom/laserpong/player2/score','devlol/h19/mainroom/laserpong/sound']):
            self.font = font
            #self.clientname = 'SHA2017Badge' + str(ubinascii.hexlify(uos.urandom(5)))
            self.clientname = 'MCH2022Badge_pongscore' + ubinascii.hexlify(network.WLAN().config("mac")).decode("UTF-8")
            self.server = server
            
            self.topics = topics
            self.clients = 0
            self.version = 44
            
            self.p1score = "0"
            self.p2score = "0"
            
            print('starting')
            #badge.init()
            #badge.leds_enable()
            #workaround for emulator

            try:
                self.owner = nvs.nvs_getstr('owner','nickname')
            except:
                self.owner ="anonycat"

            print("connecting to wifi 1 ...")

            #so we can exit anytime while connecting
            #buttons.attach(buttons.BTN_HOME, self.btn_home)

            connectToWifi()


            print (f'connecting to mqtt server:{self.server} clientname:{self.clientname}')
            self.c = MQTTClient(self.clientname,self.server)
            #,keepalive=60) # bug in umqtt, won't work
            self.c.set_callback(self.sub_cb)
            self.c.connect()
            for topic in topics:
                self.c.subscribe(topic)

            #ugfx.clear(ugfx.BLACK)
            #ugfx.flush
            #ugfx.clear(ugfx.WHITE)
            #ugfx.flush

            while True:
               self.c.wait_msg()

            # if (time.time() > last_status_update + status_update_interval):
                #  last_status_update = time.time()
                #  self.c.publish(self.statustopic, str(self.version), retain=True)



    APP_PATH = "/".join(__file__.split("/")[:-1])

    # Add Application path to sys path to import modules as if they were root modules
    sys.path.append(APP_PATH)

    scoreboard = LaserPongScoreboard()


except Exception as e:
    print("ERROR : "+ str(e))
    display.drawText(0, 0, str(e), 0x000000, "roboto_regular12")
    #display.drawText(0, 20, str(sys.exec_info()[2]), 0x000000, "roboto_regular12")
    display.flush()

    # still waiting anyway
    while True:
        time.sleep(1)