import display
import time
import wifi
import system
import buttons
import gc
import network
import ubinascii

from umqtt.simple import MQTTClient

import mch22
import nvs

def connectToWifi():
    if not wifi.status():
        wifi.connect()
        display.drawFill(display.WHITE)
        display.drawText(10, 10, "Connecting to WiFi...", 0x000000, "Roboto_Regular18")
        display.flush()
        if not wifi.wait():
            system.home()

class Pong:
    def draw_pong(self):
        display.drawText(10, 180, "https://devlol.org - up <--> down to play", 0x000000, "Roboto_Regular18")
        display.flush()
		
    def btn_up(self, pressed):
        if pressed:
            self.c.publish(("%s" % self.topic), "UP")
            display.drawText(10, 80, "UP", 0x000000, self.font)
            display.flush()
        else:
            self.c.publish(("%s" % self.topic), "STOP")
            display.drawText(10, 80, "UP RELEASED", 0x000000, self.font)
            display.flush()
			
    def btn_down(self, pressed):
        if pressed:
            self.c.publish(("%s" % self.topic), "DOWN")
            display.drawText(80, 120, "DOWN", 0x000000, self.font)
            display.flush()
        else:
            self.c.publish(("%s" % self.topic), "STOP")
            display.drawText(80, 120, "DOWN RELEASED", 0x000000, self.font)
            display.flush()
    
    def btn_a(self, pressed):
        if pressed:
            if self.player == 1:
                self.player = 2
            else:
                self.player = 1
            self.topic = self.topics[self.player - 1]
			
    def btn_home(self,pressed):
        if pressed:
            mch22.exit_python()

    def __init__(self, font="roboto_regular22",server='mqtt.devlol.org',topics=['devlol/h19/mainroom/laserpong/player1/action','devlol/h19/mainroom/laserpong/player2/action']):
        self.font = font
        self.clientname = 'MCH2022pong' + ubinascii.hexlify(network.WLAN().config("mac")).decode("UTF-8")
        self.server = server
        self.topics = topics
        self.player = 1
        self.topic = topics[0]

        print('starting')
		#workaround for emulator
        
        try:
            self.owner = nvs.nvs_getstr('owner','nickname')
        except:
            self.owner ="anonypong"
            
        self.statustopic = ("%s/%s/%s" %(self.topic, 'clientstatus', self.owner))

        print("connecting to wifi...")
		
        connectToWifi()
        
        print ("connecting to mqtt server:%s  clientname:%s" %(self.server,self.clientname))
        self.c = MQTTClient(self.clientname,self.server)
        #,keepalive=60) # bug in umqtt, won't work
        self.c.set_last_will(self.statustopic, 'OFFLINE',retain=True)
        self.c.connect()
        
        buttons.attach(buttons.BTN_HOME, self.btn_home)
        buttons.attach(buttons.BTN_DOWN, self.btn_down)
        buttons.attach(buttons.BTN_UP, self.btn_up)
        
        self.draw_pong()
        while True:
            time.sleep(0.5)
            display.drawFill(0xFFFFFF)
pong = Pong()