import threading
import socket

from loguru import logger

from dcs.tests.requestHandler import RequestHandler
from conf.config import global_var


class Server(threading.Thread):  # 将监听和处理分离， 以便同时响应多个客户端
    def __init__(self, port: 'int', buffer_size: 'int'):
        super().__init__()
        self.port: 'int' = port
        self.buffer_size = buffer_size
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind(('', port))
        global_var.server_socket = self.server_socket
        self.client_sockets: list[socket.socket] = []

    def run(self) -> None:
        self.server_socket.listen()
        while True:
            client_socket, _ = self.server_socket.accept()
            logger.debug(f'connected to client {client_socket.getpeername()}')
            self.client_sockets.append(client_socket)
            # request_header_size = struct.unpack("!Q", read_bytes(client_socket, 8))[0]
            # request_map = json.JSONDecoder().decode(read_bytes(client_socket, request_header_size).decode("utf-8"))
            # end请求要在主线程处理，不然退出就不会及时响应
            # if request_map['action'] == 'end':
            #     logger.info(f"[REQUEST] end")
            #     logger.warning("communication over!")
            #     break
            r = RequestHandler(client_socket)
            r.start()
        # self.server_socket.close()
