import network
import time
import ujson
from broker import *
from machine import Pin
from umqtt.simple import MQTTClient

# MQTTClient
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
sequence_position = 0
mqtt_message_received = False

# Definição das conexões
red_led = Pin(14, Pin.OUT)
yellow_led = Pin(27, Pin.OUT)
green_led = Pin(26, Pin.OUT)

# Definição da Sequencia
traffic_sequence = [
    (red_led, 4, "RED"),  # Vermelho por 4 segundos.
    (yellow_led, 2, "YELLOW"),  # Amarelo por 2 segundos.
    (green_led, 4, "GREEN"),  # Verde por 4 segundos.
]

"""
Conecta ao Wi-Fi
"""
def wifiConnect():
    print("Connecting to WiFi", 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!")


"""
Função de callback da inscrição no tópico
"""


def mqtt_callback(topic, msg):
    global sequence_position, mqtt_message_received
    print("[MQTT] Recieved")
    print((topic, msg))
    if msg == b"RED":
        sequence_position = 0
    elif msg == b"YELLOW":
        sequence_position = 1
    elif msg == b"GREEN":
        sequence_position = 2

    mqtt_message_received = True


"""
Conecta ao broker MQTT
"""


def MQTTConnect():
    print("Connecting to MQTT server... ", end="")
    client.set_callback(mqtt_callback)
    client.connect()
    client.subscribe(MQTT_TOPIC_RECIVE)
    print("Connected!")
    return client


"""
Reinicia LEDs
"""


def reset():
    red_led.value(0)
    yellow_led.value(0)
    green_led.value(0)


"""
Função que acende as luzes
"""


def trafficLights(client):
    global sequence_position, mqtt_message_received
    while True:
        for led, duration, color in traffic_sequence:
            client.check_msg()
            print("===================")
            print("MQTT Sequence: ", sequence_position)
            reset()  # Reinicia os LEDs
            led, duration, color = traffic_sequence[sequence_position]
            led.value(1)  # Acende o LED da sequencia
            print("[LED] " + color)
            data = ujson.dumps({"led": color})

            if mqtt_message_received:
                mqtt_message_received = False
            else:
                sequence_position = (sequence_position + 1) % len(traffic_sequence)

            try:
                client.publish(MQTT_TOPIC, data)
                print("[MQTT] Publish")
            except Exception as e:
                print(e)
            time.sleep(duration)  # Aguarda o tempo do LED


def main():
    wifiConnect()
    client = MQTTConnect()

    try:
        trafficLights(client)
    except KeyboardInterrupt:
        reset()


main()