import network
import time
from umqtt.simple import MQTTClient
import secrets

# Global variable
tsetting = False
last_tsetting = None  # Track changes

# WiFi setup
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(secrets.WIFI_SSID, secrets.WIFI_PASSWORD)

    print("Connecting to WiFi...")
    while not wlan.isconnected():
        time.sleep(1)

    print("Connected:", wlan.ifconfig())

# MQTT callback
def message_callback(topic, msg):
    topic = topic.decode()
    msg = msg.decode()

    print("Received:", topic, msg)

    if topic.endswith("/mytemperaturesetting"):
        try:
            value = int(msg)
            print("temperaturesetting value:", value)
        except:
            print("Invalid temperaturesetting value")

    elif topic.endswith("/led"):
        print("LED command:", msg)

# MQTT setup
def connect_mqtt():
    client_id = "picoW-client"
    broker = "io.adafruit.com"
    port = 1883

    username = secrets.AIO_USERNAME
    password = secrets.AIO_KEY

    client = MQTTClient(client_id, broker, port=port,
                        user=username, password=password)

    client.set_callback(message_callback)
    client.connect()

    # Feed paths
    temperaturesetting_feed = f"{username}/feeds/mytemperaturesetting"
    led_feed = f"{username}/feeds/led"

    # Subscribe
    client.subscribe(temperaturesetting_feed)
    client.subscribe(led_feed)

    print("Subscribed to feeds")
    return client, led_feed

# Publish function
def publish_led(client, led_feed, value):
    msg = "ON" if value else "OFF"
    client.publish(led_feed, msg)
    print("Published to LED feed:", msg)

# Main loop
def main():
    global tsetting, last_tsetting

    connect_wifi()
    client, led_feed = connect_mqtt()

    print("Running...")

    while True:
        client.check_msg()

        # 🔁 Example: toggle tsetting every 10 seconds (replace with real logic)
#        if int(time.time()) % 10 == 0:
#            tsetting = not tsetting

        # ✅ Only publish if value changed
        if tsetting != last_tsetting:
            publish_led(client, led_feed, tsetting)
            last_tsetting = tsetting

        time.sleep(2)

# Run
main()