import asyncio
import datetime
import re

import websockets
import logging
import threading

from pokermaster.PokerMasterDataProccesser import deal_message

logging.basicConfig(level=logging.INFO)

ip = "192.168.137.1"
port = 9999

connected_clients = set()


async def echo(websocket, path):
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            # with open("ws.log", "a") as f:
            #     time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            #     f.write(f"{time}:{message}\n")
            await deal_message(message, broadcast)
        await websocket.send("Server says: 你好,服务端收到,连接建立成功")
    except websockets.ConnectionClosed as e:
        logging.warning(f"Connection closed: {e.reason}")
    except Exception as e:
        logging.error(f"Error: {e}", exc_info=True)
    finally:
        connected_clients.remove(websocket)


async def broadcast(message):
    if connected_clients:
        await asyncio.wait([client.send(message) for client in connected_clients])
    else:
        print("No clients are connected.")


def start_cli(loop):
    while True:
        # Enter command (1: Send custom message, 2: Send JS script from file):  翻译成中文并且print
        print("输入命令 (1: 发送自定义消息, 2: 发送JS脚本):")

        command = input("请输入:")
        if command == "1":
            message = input("Enter message to send: ")
            # 在当前运行的事件循环中安排broadcast任务
            loop.call_soon_threadsafe(asyncio.create_task, broadcast(message))
        elif command == "2":
            sendJsCommand(loop)
        else:
            print("Unknown command")


def sendJsCommand(loop):
    with open("script.js", "r", encoding="utf-8") as file:
        script_content = file.read()
    # 去除script中注释的行注释或者块注释
    script_content = re.sub(r"//.*?$", "", script_content, flags=re.MULTILINE)  # 去除行注释
    script_content = re.sub(r"/\*.*?\*/", "", script_content, flags=re.DOTALL)  # 去除块注释
    # 可选:移除因为删除注释而产生的多余空行
    script_content = re.sub(r"\n\s*\n", "\n", script_content, flags=re.MULTILINE)
    # 在当前运行的事件循环中安排broadcast任务
    loop.call_soon_threadsafe(asyncio.create_task, broadcast(script_content))


async def main():
    server = await websockets.serve(echo, ip, port)
    try:
        await server.wait_closed()
    except KeyboardInterrupt:
        logging.info("Server stopped by KeyboardInterrupt")


if __name__ == '__main__':

    now = datetime.datetime.now()
    cache_date = now.strftime("%Y-%m-%d")
    cache_hour = now.strftime("%H")

    loop = asyncio.get_event_loop()
    # 在另一个线程中启动 CLI
    cli_thread = threading.Thread(target=start_cli, args=(loop,), daemon=True)
    cli_thread.start()
    try:
        loop.run_until_complete(main())
    except Exception as e:
        logging.error(f"Server error: {e}", exc_info=True)
    finally:
        loop.close()