from django.db.models.signals import post_save, post_delete, m2m_changed
from django.dispatch import receiver
from .models import RegistrationForm, Student, Guardian
from Auth.models import Profile
from N3wtSchool import settings
from N3wtSchool.redis_client import redis_client
import logging
logger = logging.getLogger(__name__)

@receiver(m2m_changed, sender=Student.guardians.through)
def check_orphan_reponsables(sender, **kwargs):
    action = kwargs.pop('action', None)
    instance = kwargs.pop('instance', None)
    # pre_clear : lors de la suppression d'une FI (on fait un "clear" sur chaque relation)
    if action in ('post_remove', 'post_clear'):
        if instance.guardians.all():
            Guardian.objects.filter(eleve=None).delete()

@receiver(m2m_changed, sender=Student.profiles.through)
def check_orphan_profils(sender, **kwargs):
    action = kwargs.pop('action', None)
    instance = kwargs.pop('instance', None)
    # pre_clear : lors de la suppression d'une FI (on fait un "clear" sur chaque relation)
    if action in ('post_remove', 'post_clear'):
        if instance.profiles.all():
            Profile.objects.filter(eleve=None).delete()
