var express = require('express');
let  router = express.Router();
let mqtt = require('mqtt');
let moment = require('moment');
const fs = require('await-fs');


const configName = "config.json"


let brenndauer = 300;                                      // 20sec Relais ON

// MQTT:
let MQTTHOST = process.env.MQTTHOST;
let MQTTPORT = process.env.MQTTPORT;
let MQTTUSR = process.env.MQTTUSR;
let MQTTPWD = process.env.MQTTPWD;


if (MQTTHOST === undefined) { MQTTHOST = 'localhost';}
if (MQTTPORT === undefined) { MQTTPORT = 1883;}
if (MQTTUSR === undefined) { MQTTUSR = "";}
if (MQTTPWD === undefined) { MQTTPWD = "";}

/*
if (MQTTHOST === undefined) { MQTTHOST = 'laufschrift.rexfue.de';}
if (MQTTPORT === undefined) { MQTTPORT = 1883;}
if (MQTTUSR === undefined) { MQTTUSR = "stwLauf";}
if (MQTTPWD === undefined) { MQTTPWD = "37CrNcgP";}
*/
// console.log("H",MQTTHOST," P",MQTTPORT," U",MQTTUSR," p",MQTTPWD);

let tio;
let connected = false;
let relais = 'MIST';
let client = mqtt.connect("mqtt://" + MQTTHOST + ":" + MQTTPORT,{username: MQTTUSR, password: MQTTPWD});
let offtime = "";
let retur = {};

console.log("Start: ", moment().format("YYYY-MM-DD HH:mm"));

client.on('connect', function() {
    connected = true;
    retur.connect = 'connected';
    client.subscribe('stat/laufschrift/POWER');
})

client.on('message',function(topix,message) {
    relais = message.toString();
    console.log("Status = ",relais);
    retur.relais = relais;
});

client.on('reconnect', function(){
   retur.connect = 'reconnect';
});


// Konfig einlesen und entsprechende Variablen einstellen
(async () => {
    try{
        let json = await fs.readFile('config/config.json','utf8')
        js = JSON.parse(json);
        if(js.brenndauer != undefined) {
            brenndauer = js.brenndauer;
        }
        console.log(brenndauer);
    }catch(err){
        console.log(err)
    }
})()


// beim start mal den Zustand abfragen
doPublish("");


function doPublish(payload) {
//    retur.relais='pending';
    client.publish('cmnd/laufschrift/Power',payload);
    if (payload == 'On') {
        offtime = moment().add(brenndauer,'s').format("HH.mm");
        tio =setTimeout(doPublish,brenndauer*1000,"Off");
        retur.offtime = offtime;
    } else if (payload == 'Off') {
        clearTimeout(tio);
        delete retur.offtime;
    }
}
// end MQTT

/* GET switch data */
router.get('/:cmd', function(req, res, next) {
    let cmd = req.params.cmd;
    let wert = req.query.wert;

    if (cmd == 'get_status') {
        doPublish("");
    } else if (cmd == 'switch_on') {
        doPublish("On");
    } else if (cmd == 'switch_off') {
        doPublish("Off");
    } else if (cmd == 'check') {

    } else {
        retur = { error: "invalid command"};
        res.json(retur);
    }
    console.log("return: ",retur)
    res.json(retur);
});


module.exports = router;
