from django.dispatch import receiver

import logging


from django.dispatch import receiver
from .custom_signals import order_confirmed
import logging
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from orders.models import Orders
from shops.models import Shop

@receiver(order_confirmed)
def order_notification(sender, **kwargs):
    try:
        order_id = kwargs.get("order_id")
        store_id = kwargs.get("store_id")
        user_ids = []
        logging.info(f"{order_id} confirmed and started via custom signal")
        shop = Shop.objects.filter(uuid = store_id).first()
        if shop:
            try:
                shop_admins = shop.unit_admin_user.all()
                for i in shop_admins:
                    user_ids.append(str(i.uuid))
            except:
                pass

        order_count = Orders.objects.filter(order_status = "Confirmed", store_uuid__uuid = store_id ).count()
        send_db_update_notification("notification", {"order_id": order_id, "count": order_count, "user_ids": user_ids})
        #
        logging.info("Signal Execution Completed")
    except Exception as e:
        logging.info(f"Signal Calling Issue: {e}")




def send_db_update_notification(message_type, msg):
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "notifications",
        {
            "type": "send_notification",
            "message": msg,
            "msg_type": message_type
        }
    )