import threading
import socket

from loguru import logger

from dcs.tools.message_process import generate_response, generate_request


class Communicator(threading.Thread):
    def __init__(self):
        super(Communicator, self).__init__()
        self.responser_list: list[tuple[str, socket.socket, dict]] = []
        self.info_list: list[tuple[tuple, dict]] = []

    def add_response(self, response_type: str, client_socket: socket.socket, response_map: dict):
        self.responser_list.append((response_type, client_socket, response_map))

    def add_info(self, info_type: str, address: tuple, info_map: dict):
        info_map.update({'type': info_type})
        self.info_list.append((address, info_map))

    def run(self) -> None:
        while True:
            for responser in self.responser_list:
                response_type, client_socket, response_map = responser[0], responser[1], responser[2]
                logger.info(f'sending response to {client_socket.getpeername()}: {response_map}')
                client_socket.sendall(generate_response(response_map))
                self.responser_list.remove(responser)

            with socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) as socket_to_client:
                for info in self.info_list:
                    socket_to_client.connect(info[0])
                    logger.info(f'sending response to {info[0]}: {info[1]}')
                    socket_to_client.sendall(generate_request(info[1]))
                    self.info_list.remove(info)
