from . import LoggingMixin

from django.conf import settings
from django.core.management.base import BaseCommand
from django.test import override_settings

from dmqtt.shortcuts import default_client_id
from dmqtt.client import Client, get_client


class Command(LoggingMixin, BaseCommand):
    def get_mqtt_client(self) -> type[Client]:
        return get_client()

    def add_arguments(self, parser):
        mqtt = parser.add_argument_group("mqtt server arguments")
        mqtt.add_argument("-u", "--user", default=settings.MQTT_USER)
        mqtt.add_argument("-P", "--password", default=settings.MQTT_PASS)
        mqtt.add_argument("-H", "--host", default=settings.MQTT_HOST)
        mqtt.add_argument("--port", default=settings.MQTT_PORT, type=int)
        mqtt.add_argument("--client-id", default=default_client_id())

        celery = parser.add_argument_group("celery arguments")
        celery.add_argument("--eager", action="store_true")

    def handle(self, eager, **kwargs):
        client = self.get_mqtt_client()(client_id=kwargs["client_id"])
        client.enable_logger()  # Use Python logging
        client.username_pw_set(kwargs["user"], password=kwargs["password"])
        # TODO Fix
        # client.tls_set()
        client.connect(kwargs["host"], kwargs["port"], 60)

        try:
            from setproctitle import setproctitle
        except ImportError:
            pass
        else:
            if client._client_id:
                setproctitle(f"[mqtt] {client._client_id.decode('utf8')}")

        with override_settings(CELERY_TASK_ALWAYS_EAGER=eager):
            # Blocking call that processes network traffic, dispatches callbacks and
            # handles reconnecting.
            # Other loop*() functions are available that give a threaded interface and a
            # manual interface.
            try:
                client.loop_forever()
            except KeyboardInterrupt:
                client.disconnect()
