from django.contrib.auth.models import Group
from rest_registration.signals import user_registered
from service.models import OtherObjects, OtherObjectsGroup, \
    OtherObjectsCategory
from django.db.models.signals import post_save
from django.dispatch import receiver


def user_created(sender, user, request, **kwargs):
    group = Group.objects.get(name='Зритель')
    group.user_set.add(user)
    user.save()


user_registered.connect(user_created)


@receiver(post_save, sender=OtherObjectsGroup)
def other_group_handler(sender, instance, **kwargs):
    OtherObjects.objects.filter(group=instance).update(visible=instance.visible)


@receiver(post_save, sender=OtherObjectsCategory)
def other_category_handler(sender, instance, **kwargs):
    objects = OtherObjectsGroup.objects.filter(category=instance)
    for obj in objects:
        obj.visible = instance.visible
        obj.save()
