"use strict";
import { logoutKeycloak } from './authentication/script.js';//qui lo script si prende il token
import RequestToDomain from './authentication/requests-to-domain.js';

const logout = document.getElementById("button-logout");
logout.addEventListener('click', () => {
    logoutKeycloak();
});

// ask domain to know which service should be used
const domain = sessionStorage.getItem('domain');
document.querySelector('body > h1').innerHTML = `Pissir SmartHome @${domain}`;
// map all elements in servicesArray to be lower case
const servicesArray = (await RequestToDomain.getUsedServices(domain)).map(s => s.toLowerCase());// ["luci", "antifurto", ...]
const userPriviledges = await RequestToDomain.getUserPriviledges(domain);// "admin" or "user"

const boolArray = [false, false, false];
let atLeastOneOfOurServices = false;
let countOurServices = 0;
for (const service of servicesArray) {
    if (service === 'antifurto') {
        boolArray[0] = true;
        atLeastOneOfOurServices = true;
	countOurServices++;
    }
    else if (service === 'scenari') {
        boolArray[1] = true;
        atLeastOneOfOurServices = true;
	countOurServices++;
    }
    else if (service === 'luci') {
        boolArray[2] = true;
        atLeastOneOfOurServices = true;
	countOurServices++;
    }
}

const antifurtoBtn = document.getElementById("antifurto-btn");
const scenariBtn = document.getElementById("scenari-btn");
const luciBtn = document.getElementById("luci-btn");

if (!atLeastOneOfOurServices) {
    document.getElementById('no-services').classList.remove('invisible');
} else {
    const api = await import('./mqtt/api.js');
    new api.default(boolArray);
    const sensori = await import('./sensori.js');
    new sensori.default();
    let usedIfOnlyOneService = null;

    // launch each class
    if (boolArray[0]){
        const antifurto = await import("./antifurto.js");
        new antifurto.default([boolArray[1],boolArray[2]]);
        antifurtoBtn.classList.remove('invisible');
	usedIfOnlyOneService = 'antifurto';
    }

    if (boolArray[1]){
        const scenari = await import("./scenari.js");
        new scenari.default([boolArray[0],boolArray[2]]);
        scenariBtn.classList.remove('invisible');
	usedIfOnlyOneService = 'scenari';
    }

    if (boolArray[2]){
        const luci = await import('./luci.js');
        new luci.default([boolArray[0],boolArray[1]]);
        luciBtn.classList.remove('invisible');
	usedIfOnlyOneService = 'luci';
    }

    // if there is only one service, click the related button
    // search if there's only one true in the boolArray
    if (countOurServices === 1) {
        const btn = document.getElementById(`${usedIfOnlyOneService}-btn`);
        btn.click();
        // btn.classList.add('invisible');
    }

    // if the user is an admin, show the admin panel
    if (userPriviledges.toLowerCase() === 'admin'){
        const admin = await import('./adminControls.js');
        new admin.default();
    }
}