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

from apps.pos_device.models import Device
from apps.warehouse.models import product_models
from .models import Notification


# @receiver(post_save, sender=InventoryEntry)
# def create_inventory_entry_notification(sender, instance, created, **kwargs):
#     """ Create notification for organization after inventory entry creation """
#
#     if not created:
#         return
#
#     def _create_notification():
#         # create notification for organization on pos device
#         devices = Device.objects.filter(assignment__client__organization=instance.organization)
#         for device in devices:
#             Notification.objects.create(
#                 device=device,
#                 organization=instance.organization,
#                 title=f" {instance.distribution.distribution_id} ورودی جدید به انبار از توزیع با کد ",  # noqa
#                 message=f' مقدار {instance.distribution.weight} کیلوگرم'  # noqa
#                         f' از توزیع با کد {instance.distribution.distribution_id} به انبار ورود خورده است ',  # noqa
#                 type='inventory',
#             )
#
#     transaction.on_commit(_create_notification)


@receiver(post_save, sender=product_models.QuotaDistribution)  # noqa
def create_quota_distribution_notification(sender, instance, created, **kwargs):
    """ Create notification for organization for quota distribution creation """

    if not created:
        return

    def _create_notification():
        # create notification for organization on pos device
        devices = Device.objects.filter(assignment__client__organization=instance.assigned_organization)
        for device in devices:
            Notification.objects.create(
                device=device,
                organization=instance.assigned_organization,
                title=f" {instance.quota.quota_id} توزیع جدید به شما از سهمیه با کد ",  # noqa
                message=f' مقدار {instance.weight} کیلوگرم'  # noqa
                        f' از سهمیه با کد {instance.quota.quota_id} به شما توزیع شده است ',  # noqa
                type='inventory',
            )

    transaction.on_commit(_create_notification)
