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

from core.apps.eggs import models


@receiver(post_save, sender=models.CourierProduct)
def create_courier_history(sender, instance, created, **kwargs):
    if created:
        models.CourierHistory.objects.create(
            courier_id=instance.courier_id,
            group_id=instance.group_id,
            get_eggs=instance.count,
            courier_product_id=instance,
            return_eggs=instance.return_eggs,
        )
        #

    else:
        histories = models.CourierHistory.objects.filter(
            courier_product_id=instance, group_id=instance.group_id
        )
        for history in histories:
            history.return_eggs = instance.return_eggs
            history.save()
