//var msgpack = require("msgpack-lite");

// Assuming paho mqtt library is included.
host = "172.16.13.130";
client = new Paho.MQTT.Client(host, port=1884, "2343");

client.onMessageArrived = onMessage;
client.onConnectionLost = onConnectionLost;

function connectToSwarmn(){
    // Only connect when person is ready.
    client.connect({onSuccess: onConnect});
}

function onConnect(){
    alert("Client Connected");
    client.subscribe("Demo");
    var buffer = msgpack.encode({"message": "Hello"});
    message = new Paho.MQTT.Message(buffer);
    message.destinationName = "Demo";

    // // Can use publish or send here.
    client.publish(message);
}

function onConnectionLost(responseObject){
    if(responseObject.errorCode !== 0){
        console.log("onConnectionLost:" + responseObject.errorMessage);
    }
}

function onMessage(message){
    alert("message received");
    // Working.
    messageb = message.payloadBytes;
    var messageD = msgpack.decode(message.payloadBytes)
    console.log(messageD)
    if(messageD["type"] == "reqvote"){
        console.log("Received vote message");
        submit_vote();
    }
}

function send_connect(){
    var buffer = msgpack.encode({"type":"connect", "sender":client.clientId, "data":{}});
    message = new Paho.MQTT.Message(buffer);
    message.destinationName = "Demo";

    client.publish(message);
}

function submit_vote(){
    // Capture the image.
    // Perform recognition on the image.
    // Send vote back to commander. 
}

function capture_image(){

}

(function(){
    var height=320;
    var width=0;
    var streaming=false;

    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton = null;

    function startUp(){
        video = document.getElementById('video');
        canvas = document.getElementById('canvas');
        photo = document.getElementById('photo');
        startbutton = document.getElementById('startbutton');

        navigator.mediaDevices.getUserMedia({ video: true, audio: false })
        .then(function(stream) {
            video.srcObject = stream;
            video.play();
        })
        .catch(function(err) {
            console.log("An error occurred! " + err);
    });
    }
})