"use strict";

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 = "browser" + 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",
    useSSL: true,
    cleanSession: false,
});

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}gpio`;
    // const subscriptionTo = `to/${mqtt_tree}webapp/#`;
    // client.subscribe(`from/${mqtt_tree}gpio/#`);
    client.subscribe(`from/${mqtt_tree}luci/#`);
    client.subscribe(`from/${mqtt_tree}scenari/#`);
    client.subscribe(`from/${mqtt_tree}antifurto/#`);
    // client.subscribe(subscriptionTo);
    isConnected = true;
    // tell every module that we're connected
    Api.isConnected = true;
}

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);
    // }
    /*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",
            onFailure: onFailure,
        });
    }, 1000);
}
// called when a message arrives
function onMessageArrived(message) {
    const topic_name = message.topic.split("/");
    if (topic_name.length < 4) return;
    const from = topic_name.pop().toLowerCase();//get the last element
    const name_content = message.payloadString.split(":");
    const rawValue = cleanItem(name_content[1]);
    const valueInt = parseInt(rawValue);
    const messageJSON = JSON.parse(message.payloadString);
    if (message.topic.startsWith(`from/${mqtt_tree}luci`)) {
        if (from === 'luci')
            Api.sendDataLuciWeb(messageJSON);
        else if (from === 'new')
            Api.sendWebNewLuci(messageJSON);
        else if (from === 'sensore')
            Api.sendWebNewSensore(messageJSON);
        else if (from === 'luce')
            Api.sendLuciStatoWeb(messageJSON);
        return;
    }
    if (message.topic.startsWith(`from/${mqtt_tree}scenari`)) {
        if (from === 'scenari'){
            if (messageJSON.status != null){//escludo le luci
                console.log('ricevuto roba inutile',messageJSON)
                return;
            }
            if(messageJSON.learnINbtn != null){
                Api.sendWebConfiguration(messageJSON);
                return;
            }
            //else it's RPC
            Api.sendScenariWeb(messageJSON);
        }
        else if (from === 'attiva'){
            console.log('cambiostatoscenario',rawValue)
            Api.sendWebNewScenarioStatus(rawValue);
        }
        else if (from === 'learn')
            Api.sendWebScenarioAutoma(rawValue == 'true');
        else if (from === 'antifurto')
            Api.overlayScenariAntifurto(rawValue == 'true');
        else if (from === 'salva')
            Api.sendWebSavedScenario(messageJSON);
        else if (from === 'attivazioneautomatica') {
            console.log('leggiattivazioneautomaticascenari',rawValue)
            Api.sendWebScenarioAttivoAutomatico(rawValue);
        }
        return;
    }
    if (message.topic.startsWith(`from/${mqtt_tree}antifurto`)) {
        if (from === 'antifurto' && topic_name[topic_name.length - 1] === 'antifurto')
            // qui dopo aver dato set stato (scenari -> cmd -> event -> ... -> qui)
            Api.overlayAntifurtoAntifurto(rawValue == 'true');
        else if (from === 'antifurto'){
            // dopo rpc per descrizione
            if(messageJSON.antifurto != null)
                Api.sendWebGetAntifurto(messageJSON);
        } else if (from === 'valore')
            Api.setAntifurtoAttenzione(valueInt);
        else if (from === 'allarme')
            Api.setAntifurtoAllarme(rawValue == 'true');
        else if (from === 'soglia')
            Api.sendWebSoglia(valueInt);
        return;
    }
    console.log('impossibile', message.topic, message.payloadString);
}

// funzioni del prof
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;
}*/