import paho.mqtt.client as mqtt
import umsgpack

class BallotVoter:
    def __init__(self, on_vote):
        self.client = mqtt.Client()
        # id is generated automatically.
        self.client.connect('172.16.13.128')
        self.on_vote = on_vote

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

        self.client.subscribe('swarm1/voters', qos=1)

        # Create the message to send that it is now part of the swarm.

        # Need to set a will as well to broadcast on unexpected disconnection, so commander
        # knows it is no longer part of the set of voters. 
        # Leaving this until core centralised system is working.
        #will_message = {"type": "UDisconnect"}

        self.send_connect()

    def on_message(self, client, userdata, message):
        messageDict = umsgpack.unpackb(message)
        if "type" in messageDict.keys:
            # Ok message.
            if messageDict["type"] == "reqVote":
                self.submit_vote()
            if messageDict["type"] == "listening":
                self.send_connect()
        else:
            # Bad message.
            pass

    def submit_vote(self):
        binary = umsgpack.packb("type": "vote", "client": self.client._client_id, "vote": self.on_vote())
        self.client.publish('swarm1/commander', binary)
        
    def send_connect(self):
        # Send a connected message to let any commanders know that 
        # it is available. 
        binary = umsgpack.packb({"type": "connect", "id": self.client._client_id})
        self.client.publish("swarm/commander", binary)