from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.db.models import Sum, Count, Q
from .models import LiveStock


def update_herd_statistics(instance: LiveStock):
    """
    update light & heavy livestock number in rancher herd
    """
    counts = LiveStock.objects.filter(
        herd__rancher=instance.herd.rancher,
        herd=instance.herd
    ).aggregate(
        light_livestock_number=Count('id', filter=Q(weight_type='L')),
        heavy_livestock_number=Count('id', filter=Q(weight_type='H'))
    )

    instance.herd.light_livestock_number = counts['light_livestock_number']
    instance.herd.heavy_livestock_number = counts['heavy_livestock_number']
    instance.herd.save(update_fields=['light_livestock_number', 'heavy_livestock_number'])


@receiver(post_save, sender=LiveStock)
def update_herd_on_livestock_save(sender, instance, **kwargs):
    update_herd_statistics(instance)


@receiver(post_delete, sender=LiveStock)
def update_herd_on_livestock_delete(sender, instance, **kwargs):
    update_herd_statistics(instance)
