from django.db.models import signals
from django.dispatch import receiver

from lms.courses.models import Course
from lms.courses.services import update_course_on_change_group

from .models import EnrolledUser, Enrollment
from .services import (
    delete_course_and_group_participants, enroll_type_instant_change_status, update_course_and_group_participants,
    update_default_enrollment, update_enrolled_user_groups, update_or_create_course_student,
)


@receiver(signal=signals.pre_save, sender=EnrolledUser)
def enrolled_user_pre_save_handler(instance: EnrolledUser, **kwargs):
    update_enrolled_user_groups(instance)
    enroll_type_instant_change_status(enrolled_user=instance)


@receiver(signal=signals.post_save, sender=EnrolledUser)
def enrolled_user_post_save_handler(instance: EnrolledUser, **kwargs):
    update_or_create_course_student(enrolled_user=instance)
    update_course_and_group_participants(enrolled_user=instance)
    update_course_on_change_group(course=instance.course)


@receiver(signal=signals.post_delete, sender=EnrolledUser)
def enrolled_user_post_delete_handler(instance: EnrolledUser, **kwargs):
    delete_course_and_group_participants(instance)


@receiver(signal=signals.post_save, sender=Enrollment)
def enrollment_post_save_handler(instance: Enrollment, **kwargs):
    update_default_enrollment(enrollment=instance)


@receiver(signal=signals.post_save, sender=Course)
def course_post_save_handler(instance: Course, **kwargs):
    if instance.course_type == instance.TypeChoices.TRACK:
        Enrollment.objects.get_or_create(
            course=instance,
            name=instance.name,
            enroll_type=Enrollment.TYPE_INSTANT,
            is_default=True,
        )
