# Standard Library
import logging

# Django
from django.db.models.signals import post_save
from django.dispatch import receiver

from incursions.app_settings import INCURSIONS_AUTO_HIGHSEC_FOCUS
from incursions.models.incursion import Focus, Incursion
from incursions.models.waitlist import Waitlist
from incursions.tasks import (
    incursion_boss_spawned, incursion_ended, incursion_established, incursion_mobilizing, incursion_withdrawing,
    waitlist_state,
)

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Incursion)
def incursion(sender, instance: Incursion, created: bool, *args, **kwargs):  # - simple signal
    update_fields = kwargs.pop('update_fields', []) or []

    if created:
        incursion_established.delay(instance.pk)
        if INCURSIONS_AUTO_HIGHSEC_FOCUS and instance.is_high_sec:
            focus = Focus.get_solo()
            if getattr(focus, 'incursion_id', None) != instance.pk:
                focus.incursion = instance
                focus.save(update_fields=["incursion"])

    if 'state' in update_fields:
        match instance.state:
            case Incursion.States.MOBILIZING:
                incursion_mobilizing.delay(instance.pk)
            case Incursion.States.WITHDRAWING:
                incursion_withdrawing.delay(instance.pk)
            case Incursion.States.ENDED:
                incursion_ended.delay(instance.pk)
            case _:
                pass  # Established handled on creation

    if 'has_boss' in update_fields and instance.has_boss:
        incursion_boss_spawned.delay(instance.pk)


@receiver(post_save, sender=Waitlist)
def waitlist(sender, instance: Waitlist, created: bool, *args, **kwargs):  # - simple signal
    update_fields = kwargs.pop('update_fields', []) or []
    if 'is_open' in update_fields:
        waitlist_state.delay(instance.pk, instance.is_open)
