"use strict";

import ApiMqttIn from "./api-mqtt-in.js";
import Api from "./api.js";

// Create a client instance
const mqtt_domain = "gruppo2";
const mqtt_subdomain = "luci";
const mqtt_tree = mqtt_domain + "/" + mqtt_subdomain + "/";
export { mqtt_tree };
const d = new Date();
const clientid = "test" + d.getTime();
// const host = location.host.split(":");
// const mqtthost = host[0];
const mqtthost = "luci.local";

const client = new Paho.MQTT.Client(mqtthost, 9001, clientid);
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.onFailure = onFailure;

// connect the client
client.connect({
    onSuccess: onConnect,
    userName: "gruppo2",
    password: "funziona",
});

let isConnected = false;

function sendMessage(topic, message, retryNum = 0) {
    if (isConnected) {
        const message_ = new Paho.MQTT.Message(message);
        message_.destinationName = topic;
        client.send(message_);
    } else if (retryNum < 3) {
        setTimeout(() => {
            sendMessage(topic, message, retryNum++);
        }, 1000);
    } else {
        console.log('impossibile inviare il messaggio')
        throw new Error('impossibile inviare il messaggio');
    }
}

export { sendMessage };

// called when the client connects
function onConnect() {
    // Once a connection has been made, make a subscription and send a message.
    const subscriptionFrom = `from/${mqtt_tree}#`;
    const subscriptionTo = `to/${mqtt_tree}webapp/#`;
    client.subscribe(subscriptionFrom);
    client.subscribe(subscriptionTo);
    isConnected = true;
    // tell every module that we're connected
    Api.isConnected = true;
    console.log('connected');
}

function onFailure(message) {
    console.log("onFailure:\t" + message.errorMessage);
    console.log(message)
}

// called when the client loses its connection
function onConnectionLost(responseObject) {
    // if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:" + responseObject.errorMessage);
    // }
    /*const interval = setInterval(() => {
        console.log('retrying connection');
        client.connect({
            onSuccess: onConnect,
            userName: "gruppo2",
            password: "funziona",
        });
    }, 1000);
    setTimeout(() => {
        clearInterval(interval);
        console.log('done retrying');
    }, 10000);//after 10 tries, stop trying*/
    setTimeout(() => {
        console.log('retrying connection');
        client.connect({
            onSuccess: onConnect,
            userName: "gruppo2",
            password: "funziona",
        });
    }, 1000);
}

// called when a message arrives
function onMessageArrived(message) {
    console.log(message.topic, message.payloadString);
    // console.log(message.destinationName+", "+message.payloadString);
    const topic_name = message.topic.split("/");
    if (topic_name.length < 4) return;
    const from = topic_name.pop().toLowerCase();//get the last element
    if (topic_name[0] === 'to') {
        if(from === 'luci'){
            // TODO
        } else if(from === 'scenari'){
            // TODO
        } else if(from === 'antifurto'){
            // TODO
        } else {
            onFailure({errorMessage:'from non riconosciuto'});
        }
        return;
    } else if (topic_name[0] === 'from') {
        const name_content = message.payloadString.split(":");
        const valueInt = parseInt(cleanItem(name_content[1]));
        const valueBoolean = valueInt === 1;
        if (message.topic.startsWith(`from/${mqtt_tree}gpio/`)) {
            const whatHappened = cleanItem(name_content[0]).toLowerCase();
            if(whatHappened === 'status')
                ApiMqttIn.readStatusLuci(from, { stato: valueBoolean });
            else if (whatHappened === 'event'){
                if(from.startsWith('out'))
                    ApiMqttIn.triggerLuce(from, { evento: valueInt });
            }
            return;
        }
        if (message.topic.startsWith(`from/${mqtt_tree}scenari`)) {
            if(from === 'scenari')
                ApiMqttIn.readAllRPCScenari(JSON.parse(message.payloadString));
            else if(from === 'attiva')
                ApiMqttIn.cambioStatoScenario({nome:valueBoolean});
            else if(from === 'learn')
                ApiMqttIn.readStatoAutomaScenario(valueInt);
            else if(from === 'antifurto')
                ApiMqttIn.readStatoAutomaAntifurto(valueInt);
            else if(from === 'salva')
                ApiMqttIn.renamedSavedScenario(message.payloadString);
            return;
        }
        return;
    }
    /*if (name.includes("IN"))
        field_update(name, value);
    else
        button_update(name, value);*/
}

function cleanItem(item) {
    let citem = "";
    for (let i = 0; i < item.length; i++)
        if (item[i] != '"' && item[i] != '}' && item[i] != '{' && item[i] != '\n')
            citem += item[i];
    return citem;
}

/*function normalizeValue(value, digit) {
    let res = "";
    let n = 0;
    let dot = false;
    for (i = 0; i < value.length && n < digit; i++) {
        res += value[i];
        if (dot == true) n++;
        if (value[i] == '.') dot = true;
    }
    return res;
}

function getNamefromTag(name) {
    const names = name.split("-");
    if (names.length > 1)
        return names[1];
    else
        return "";
}

function button_update(name, value) {//this is pretty much useless now
    return;
    const id = "I_" + name;
    const image = document.getElementById(id);
    if (image == null) return;
    if (value == "false" || value < 1) {
        image.src = "/res/led-green.png"
    } else {
        image.src = "/res/led-red.png"
    }
    return;
}


function field_update(name, value) {
    const el = document.getElementById(name)
    if (el == null) return;
    el.innerHTML = value;
    // const pname = "#" + name;
    // $(pname).text(value);//questo non funziona
}

doClick = function (name) {
    const id = "I_" + name;
    const image = document.getElementById(id);
    if (image.src.includes("led-green.png")) {
        mqtt_message = new Paho.MQTT.Message("{cmd:1}");
        mqtt_message.destinationName = "to/" + mqtt_domain + "/" + mqtt_subdomain + "/gpio/" + name;
        client.send(mqtt_message);
    }
    else {
        mqtt_message = new Paho.MQTT.Message("{cmd:0}");
        mqtt_message.destinationName = "to/" + mqtt_domain + "/" + mqtt_subdomain + "/gpio/" + name;
        client.send(mqtt_message);
    }
    return;
}*/