from datetime import timedelta, datetime

from source import managers, packets, structures
from source.behaviors.roles import base, UndefinedRole
from source.utils.crypto.type import CipherType


class SlaveRole(base.BaseRole):
    """
    Role used when the machine is declared as a slave.
    It shall listen for a master and check if everything is working properly
    """

    def __init__(self, manager: "managers.Manager", master_address: tuple):
        super().__init__(manager)

        # the address of the server
        self.master_address = master_address

    def handle(self):
        # if we don't have any secret key for this server, request it
        # TODO(Faraphel): the secret key might be stored somewhere else than here, or need to be reset
        if self.manager.communication.secret_key is None:
            packet = packets.RequestKeyPacket()
            self.manager.communication.send(packet, CipherType.AES_CBC, self.master_address)

        # check if the master interacted recently
        master_peer: structures.Peer = self.manager.peer.peers[self.master_address]
        if datetime.now() - master_peer.last_interaction > timedelta(seconds=10):
            self.manager.role.current = UndefinedRole(self.manager)
