# tasks.py

from celery import shared_task
from celery.utils.log import get_task_logger
from .process import RelayProcess
from .models import Device

logger = get_task_logger(__name__)

class RelayTaskManager:

    def __init__(self):
        self.active_relay = {}

    def start_relay(self, uuid):
        if uuid not in self.active_relay:
            relay = RelayProcess(uuid)
            relay.start()
            self.active_relay[uuid] = relay
        else:
            logger.info(f"Relay {uuid} already running!...")

    def stop_relay(self, uuid):
        if uuid in self.active_relay:
            self.active_relay[uuid].stop()
            del self.active_relay[uuid]

    def stop_all_relay(self):
        for _, relay in self.active_relay.items():
            relay.stop()
        self.active_relay.clear()

    def start_all_relay(self):
        all_relays = Device.all_devices()
        for relay in all_relays:
            self.start_relay(relay.uuid)


task_manager = RelayTaskManager()


@shared_task(bind=True)
def relay_start(self, uuid):
    task_manager.start_relay(uuid)
    return f"Relai {uuid} démarré."


@shared_task(bind=True)
def relay_stop(self, uuid):
    task_manager.stop_relay(uuid)
    return f"Relai {uuid} arrêté."


@shared_task(bind=True)
def relay_stop_all(self):
    task_manager.stop_all_relay()
    return "Touts les Relais arrêtées."


@shared_task(bind=True)
def relay_start_all(self):
    task_manager.start_all_relay()
    return "Touts les Relais en cours de démarrage."

