from models import WebSocket
from logger import logger
import json, asyncio
from starlette.websockets import WebSocketState
class ConnectionManager:
    is_connected = False
    def __init__(self):
        self.active_connections: list[WebSocket] = []

    def jsonMessage(self, code=0, msg="", data: object = None,msg_type=""):
        """json字符串数据"""
        jsonData = {"code": code, "msg": msg, "data": data, "msg_type": msg_type}
        return jsonData

    async def connect(self, websocket: WebSocket):
        '''连接事件'''
        await websocket.accept()
        self.is_connected = True
        self.active_connections.append(websocket)
        logger.info("socket 已连接")

    def disconnect(self, websocket: WebSocket):
        '''断开连接事件'''
        self.active_connections.remove(websocket)
        logger.info("socket 连接断开")

    async def send_personal_message(self, message: str, websocket: WebSocket):
        '''向用户发送消息'''
        # await websocket.send_json(message)
        await websocket.send_json(message)

    async def broadcast(self, message: str):
        """广播消息"""
        for connection in self.active_connections:
            if connection.client_state == WebSocketState.DISCONNECTED:
                continue
            print("正在发送广播消息", "message", connection.client_state)
            await connection.send_json(message)
