import json
from DecisionSystem.messages import ConnectSwarm, SubmitVote, Message, deserialise, RequestVote, ClientVoteRequest, VoteResult
from multiprocessing import Pool
from messenger import Messenger

class BallotVoter:
    def __init__(self, on_vote, handle_agreement, messenger: Messenger):
        self.messenger = messenger
        self.messenger.add_message_callback(self.on_message)
        self.messenger.add_connect(self.on_connect)
        self.on_vote = on_vote
        self.handle_agreement = handle_agreement

    def on_connect(self, rc):
        print("Connected with result code " + str(rc))

        # Tell commander we are now connected.
        self.send_connect()

    def on_message(self, message):
        print("Message Received!")
        messageD = deserialise(message.payload)
        print("Message Type: " + messageD.type)
        # Ok message.
        if messageD.type == RequestVote().type:
            print('Received vote message')
            self.submit_vote()
        elif messageD.type == "listening":
            self.send_connect()
        elif messageD.type == VoteResult.type:
            self.handle_agreement(messageD.data["vote"])

    def submit_vote(self):
        v = self.on_vote()
        if v == None:
            print('Could not get vote')
            return
        print("Got Vote")
        vote = SubmitVote(v, self.messenger.id)
        print('Created Vote Message')
        self.messenger.broadcast_message(self.messenger.swarm, vote.serialise())
        print('published vote')

    def send_connect(self):
        # Send a connected message to let any commanders know that 
        # it is available. 
        self.messenger.broadcast_message(self.messenger.swarm, ConnectSwarm(self.messenger.id).serialise())

    def request_vote(self):
        """Sends a request to the leader to start collecting votes."""
        self.messenger.broadcast_message(self.messenger.swarm, ClientVoteRequest(self.messenger.id).serialise())