from threading import Thread
from queue import Queue
from socket import socket
from logging import getLogger


class Sender(Thread):
    def __init__(self, connection_queue: "Queue[Event]", connection: socket, connection_id: int) -> None:
        super(Sender, self).__init__()
        self.connection_queue = connection_queue
        self.connection = connection
        self.logger = getLogger(f"Sender - {connection_id}")

    def run(self) -> None:
        while True:
            message = self.connection_queue.get()
            self.logger.debug("sending %s",  len(message))
            message_size = len(message)
            try:
                self.connection.send(message_size.to_bytes(8, "big", signed=False) + message)
            except BrokenPipeError:
                self.connection_queue.put(message)
                return
            except Exception:
                self.connection_queue.put(message)
                return
            self.logger.debug("send %s",  len(message))
