var mqtt = require('mqtt');

var mqttClient = function () {

    var orgId = "qz0da4";
    var userName = "a-qz0da4-dfwwdkmkzr";
    var appKey = "9txJEf3Cjy7hkSOvkv";

    this.projector = 'ProjectorISP15';
    this.lighting = 'LightingISP15';

    this.connected = false;

    var options = {
        keepalive: 3600,
        clientId: "a:" + orgId + ":" + Date.now(),
        username: userName,
        password: new Buffer(appKey)

    };

    this.client = mqtt.connect('mqtt://' + orgId + '.messaging.internetofthings.ibmcloud.com', options);

    this.client.on('connect', function () {
        connected = true;
        console.log('Connected to IBM');
    });

    this.isConnected = function () {
        return this.connected;
    }
};



mqttClient.prototype.projectorOn = function () {

    var destinationName = "iot-2/type/Ti-CC3200/id/" + this.projector + "/cmd/" + 'ON' + "/fmt/json";
    this.client.publish(destinationName, 'ON');
};

mqttClient.prototype.projectorOff = function () {
   
    var destinationName = "iot-2/type/Ti-CC3200/id/" + this.projector + "/cmd/" + 'OFF' + "/fmt/json";
    this.client.publish(destinationName, 'OFF');
};


mqttClient.prototype.lightsOn = function () {
   
    var destinationName = "iot-2/type/Ti-CC3200/id/" + this.lighting + "/cmd/" + 'o' + "/fmt/json";
    this.client.publish(destinationName, 'o');
    destinationName = "iot-2/type/Ti-CC3200/id/" + this.lighting + "/cmd/" + 'n' + "/fmt/json";
    this.client.publish(destinationName, 'n');
};

mqttClient.prototype.lightsOff = function () {
   
    var destinationName = "iot-2/type/Ti-CC3200/id/" + this.lighting + "/cmd/" + 'f' + "/fmt/json";
    this.client.publish(destinationName, 'f');
    destinationName = "iot-2/type/Ti-CC3200/id/" + this.lighting + "/cmd/" + 'g' + "/fmt/json";
    this.client.publish(destinationName, 'g');
};

module.exports.mqttClient = mqttClient;