"""Websocket Connection Manager."""

from fastapi import WebSocket

from app.api.v1.auth import get_session_from_websocket
from app.services.database import DatabaseService

db_service = DatabaseService()


class ConnectionManager:
    """Connection manager for handling WebSocket connections."""

    def __init__(self):
        """Initialize the connection manager."""
        self.active_connections: list[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        """Accept a WebSocket connection and add it to the active connections."""
        await websocket.accept()

        # session = await get_session_from_websocket(websocket)
        # if session is None:
            # return  # Already closed inside auth function
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        """Remove a WebSocket connection from the active connections."""
        if websocket in self.active_connections:
            self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        """Send personal message."""
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        """Broadcasting."""
        for connection in self.active_connections:
            await connection.send_text(message)


'''
class ConnectionManager:
    """Connection manager class."""

    def __init__(self):
        """Init function."""
        # Store active connections as {room_id: {user_id: WebSocket}}
        self.active_connections: Dict[int, Dict[int, WebSocket]] = {}

    async def connect(self, websocket: WebSocket, room_id: int, user_id: int):
        """Establishes a connection with the user. websocket.accept() — confirms the connection."""
        await websocket.accept()
        if room_id not in self.active_connections:
            self.active_connections[room_id] = {}
        self.active_connections[room_id][user_id] = websocket

    def disconnect(self, room_id: int, user_id: int):
        """Closes the connection and removes it from the list of active ones connections. If there are no more users in the room, deletes the room."""
        if room_id in self.active_connections and user_id in self.active_connections[room_id]:
            del self.active_connections[room_id][user_id]
            if not self.active_connections[room_id]:
                del self.active_connections[room_id]

    async def broadcast(self, message: str, room_id: int, sender_id: int):
        """Broadcasts a message to all users in the room."""
        if room_id in self.active_connections:
            for user_id, connection in self.active_connections[room_id].items():
                message_with_class = {"text": message, "is_self": user_id == sender_id}
                await connection.send_json(message_with_class)
'''

"""
@router.websocket("/{room_id}/{user_id}")
async def websocket_endpoint(websocket: WebSocket, room_id: int, user_id: int, username: str): 
    await manager.connect(websocket, room_id, user_id) 
    await manager.broadcast(f"{username} (ID: {user_id}) has joined the chat.", room_id, user_id) 

    try: 
        while True: 
            data = await websocket.receive_text() 
            await manager.broadcast(f"{username} (ID: {user_id}): {data}", room_id, user_id) 
    except WebSocketDisconnect: 
        manager.disconnect(room_id, user_id) 
        await manager.broadcast(f"{username} (ID: {user_id}) has left the chat.", room_id, user_id)
"""
