print("It's happening!")
from DecisionSystem.CentralisedDecision.ballotvoter import BallotVoter
from DecisionSystem.CentralisedDecision.messenger import MqttMessenger
import numpy as np
import cv2
import time
import argparse
import os.path
import sys
from GestureRecognition.simplehandrecogniser import SimpleHandRecogniser
from threading import Thread
from queue import Queue

import MyRaft.node as raft
import MyRaft.leader as leader
import DecisionSystem.CentralisedDecision.commander as commander
import DecisionSystem.CentralisedDecision.messenger as messenger
import DecisionSystem.CentralisedDecision.ballotvoter as voter

print("Parsing args")
parser = argparse.ArgumentParser(description="Runs a file with OpenCV and gets consensus from the swarm.")

parser.add_argument('-V', '--video', help="Path to video file.")

args = parser.parse_args()

recogniser = SimpleHandRecogniser(None)

# Checks if video file is specified and if that file exists.
if(args.video):
    print('finding video')
    if not os.path.isfile(args.video):
        print("Input video file ", args.video, " doesn't exist")
        sys.exit(1)
else:
    # Exit if no video file specified - we aren't using webcam here.
    sys.exit(1)

def on_vote():
    # Get the current frame of the camera and process what hand 
    # is currently being seen. 
    print('getting frame')
    # Need to copy rather than just take a reference, as frame will
    # constantly be changing.
    global vd
    recogniser.set_frame(np.copy(vd.frame))
    print('Got frame, voting with recogniser')
    return recogniser.get_gesture()

def connect_to_broker(mqtt):
    print("Connecting to broker")
    max_collisions = 100
    collisions = 1
    while not mqtt.connect() and collisions <= max_collisions:
        time.sleep(2 ** collisions - 1)
        print("Reconnecting in %s" %(2 ** collisions - 1))
        collisions += 1

mqtt = MqttMessenger()
v = BallotVoter(on_vote, mqtt)

def on_disconnect(rc):
    print("Client disconnected from broker")
    i = input("Would you like to reconnnect? (y|n)")
    if i == 'y':
        global mqtt
        connect_to_broker(mqtt)

mqtt.add_disconnect_callback(on_disconnect)
connect_to_broker(mqtt)

# Start the video capture at the next whole minute.
current_time_sec = time.gmtime(time.time()).tm_sec
if current_time_sec < 40:
    time.sleep(60 - current_time_sec)
else:
    time.sleep(60 - current_time_sec + 60)
print('loading video')



print('Press q to quit the server, g to get votes/consensus')

while True:
    if vd.frame is None:
        continue
    frame = np.copy(vd.frame)
    cv2.imshow('Frame', frame)
    k = cv2.waitKey(33)
    if k == ord('q'):
        break
    elif k == -1:
        continue
    elif k == ord('g'):
        # Get votes
        pass
