import json
import logging
from channels.generic.websocket import AsyncWebsocketConsumer

logger = logging.getLogger(__name__)

connected_websocket_consumers = 0

class ActivityConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        global connected_websocket_consumers
        
        if "url_route" not in self.scope:
            raise ValueError
        
        self.event_id = self.scope["url_route"]["kwargs"]["event_id"]
        
        logger.debug(f"Connection for Event={self.event_id}")
        
        # Subscribe to database changes for this event
        await self.channel_layer.group_add(
            f"activity_{self.event_id}",
            self.channel_name
        )
        
        await self.accept()
        
        connected_websocket_consumers += 1
        
        logger.debug(f"Websocket for Event={self.event_id} opened ({connected_websocket_consumers} total)")
        
        
        await self.update_connected()
        

    async def disconnect(self, close_code):
        global connected_websocket_consumers
        logger.debug(f"Disconnection for Event={self.event_id}")
        
        # Remove from group on disconnect
        await self.channel_layer.group_discard(
            f"activity_{self.event_id}",
            self.channel_name
        )
        connected_websocket_consumers -= 1
        
        logger.debug(f"Websocket for Event={self.event_id} closed ({connected_websocket_consumers} total)")
        
        await self.update_connected()


    async def update_connected(self):
        """Update all connected """
        logger.debug("Sending connected update...")
        
        await self.channel_layer.group_send(
                f"activity_{self.event_id}",
                {
                    "type": "group.message",
                    "activity_json": {} # connected will be filled
                }
            )


    async def group_message(self, event):
        global connected_websocket_consumers
        
        logger.debug(f"Message {self.event_id}: {event}")
        
        activity_json = event.get("activity_json")
        logger.debug("Ready to send: " + str(activity_json))
        if activity_json is not None:
            activity_json["connected"] = connected_websocket_consumers
            activity_str = json.dumps(activity_json)
        
            logger.debug("Sending: " + str(activity_str))
        
            await self.send(text_data=activity_str)