import time

from source import packets, structures
from source.managers import Manager
from source.utils.crypto.type import CipherType
from source.utils.dict import TimestampedDict


class PeerManager:
    """
    Manage the peers network
    """

    def __init__(self, manager: "Manager"):
        self.manager = manager

        # set of addresses associated to their peer
        self.peers: TimestampedDict[tuple, structures.Peer] = TimestampedDict()

    def handle(self) -> None:
        # send requests to discover new peers
        packet = packets.DiscoveryPacket()
        self.manager.communication.broadcast(packet, CipherType.PLAIN)

    def loop(self) -> None:
        while True:
            self.handle()

            # TODO(Faraphel): adjust sleep time ? as much seconds as there are peer to avoid flooding the network ?
            time.sleep(1)
