import network
import time
from machine import Pin, I2C
from umqtt.simple import MQTTClient

from ssd1306 import SSD1306_I2C
from board import *

DISPLAY_WIDTH = 128
DISPLAY_HEIGHT = 64

MQTT_CLIENT_ID = "689f0309-adcc-477d-b137-a2e0b75a9829"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_BOARD_TOPIC = "elsys/ttt/board"
MQTT_PLAYER_TOPIC = "elsys/ttt/player"

def connect_to_wifi():
    print("Connecting to Wi-Fi", end="")
    sta_if = network.WLAN(network.STA_IF)
    sta_if.active(True)
    sta_if.connect('Wokwi-GUEST', '')
    while not sta_if.isconnected():
        print(".", end="")
        time.sleep(0.1)
    print(" Connected!")

def connect_to_mqtt_broker():
    connect_to_wifi()
    print("Connecting to MQTT server... ", end="")
    client.connect()
    print("Connected!")
    client.subscribe(MQTT_BOARD_TOPIC)
    print("Subscribed to {}".format(MQTT_BOARD_TOPIC))

""" STATUS CODES
-2       -> It's player's turn
-1       -> Successfull move
0 and 1  -> Game over!
2        -> It's not your turn!
3        -> Invalid move! Try again!
"""
def mqtt_client_callback(topic, message):
    global client, board

    topic = topic.decode("utf-8")
    message = message.decode("utf-8")

    print("Received from MQTT topic: {} - message: {}".format(topic, message))

    # Message format: player:x,y
    player, move = message.split(":")
    x, y = list(map(lambda el: int(el), move.split(",")))

    status, message = board.make_move(player, x, y)

    if status == -1:
        client.publish("{}/{}".format(MQTT_PLAYER_TOPIC, player), message)
        client.publish("{}/{}".format(MQTT_PLAYER_TOPIC, board.curr_player.lower()), "-2:It's your turn!")
    elif status == 0 or status == 1:
        client.publish("{}/{}".format(MQTT_PLAYER_TOPIC, "x"), message)
        client.publish("{}/{}".format(MQTT_PLAYER_TOPIC, "o"), message)
    elif status == 2 or status == 3:
        client.publish("{}/{}".format(MQTT_PLAYER_TOPIC, player), message)


client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(mqtt_client_callback)
connect_to_mqtt_broker()

i2c = I2C(0, scl=Pin(22), sda=Pin(21))
display = SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)

board = Board(display)
board.print_board_on_display()

try:
    while True:
        client.wait_msg()
finally:
    client.disconnect()