import json
from websocket_server import WebsocketServer
moon_addr = "127.0.0.1"
clients = dict() # id -> name
clients_rev = dict() # name -> id
clients_connection = dict() # id -> client obj

def new_client(client, server):
    clients_connection[client["id"]] = client
    print(f"新客户端连接: {client['id']}")
    
def client_left(client, server):
    print(f"客户端断开连接: {client['id']}")
    # 连接关闭时从集合中移除
    if client in clients.values():
        clients.pop(clients_rev[client['id']])
        clients_rev.pop(client['id'])

def message_received(client, server, message):
    print(f"处理信息: {message}")
    try:
        msg = json.loads(message)
        clients[msg["id"]] = client['id']
        clients_rev[client['id']] = msg["id"]
        if msg["sendto"] == "auth":
            return
        try:
            server.send_message(clients_connection[clients[msg["sendto"]]], msg["content"])
        except KeyError:
            print("无法发送至端点")
    except json.JSONDecodeError:
        print("无法解码 JSON 消息")

def main():
    server = WebsocketServer(host=f'{moon_addr}', port=8765)
    server.set_fn_new_client(new_client)
    server.set_fn_client_left(client_left)
    server.set_fn_message_received(message_received)
    
    print(f'启动"卫星"中继服务器: ws://{moon_addr}:8765')
    server.run_forever()

if __name__ == "__main__":
    main()
