import * as state from "../state/state.js";

const accessControlLevelCodes = ["delete", "execute", "read", "use", "write"]; // should be in sorted order
const metricSuffixValues = ["k", "M", "B", "T", "P", "E"];
const chartAnimations = document.querySelector(".chart-animations");
const enablePrivilege = document.querySelector("#enable-privilege");
const useDefaultPrivilege = document.querySelector("#default-privilege");
const useCustomPrivilege = document.querySelector("#custom-privilege");
const customPrivilegeValue = document.querySelector(".custom-privilege-value");
const baseGridTheme = document.querySelector(".base-grid-theme");
const linksAccess = document.querySelector(".links-access");
const contextMenuAccess = document.querySelector(".context-menu-access");
const rtlSupport = document.querySelector(".rtl-support");
const negativeValueFormat = document.querySelector(".negative-value-format");
const seriesColorsLimit = document.querySelector(".series-colors-limit");
const accessControlLevels = document.querySelectorAll(".access-control-level");
const metricSuffixes = document.querySelectorAll(".metric-suffix");
const ibcsByDefault = document.querySelector(".ibcs-default");
const actualDataType = document.querySelector(".actual-data-type");
const forecastDataType = document.querySelector(".forecast-data-type"); 
const plannedDataType = document.querySelector(".planned-data-type");
const previousDataType = document.querySelector(".previous-data-type");
const negativeMetrics = document.querySelector(".negative-metrics");

enablePrivilege.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    if (e.target.checked) {
        useDefaultPrivilege.disabled = false;
        useCustomPrivilege.disabled = false;
        state.updateSettingsData("enablePrivilegeForEditor", "1");

        if (useCustomPrivilege.checked) {
            customPrivilegeValue.disabled = false;
        }

        if (customPrivilegeValue.value.trim() !== "") {
            state.updateSettingsData("checkPrivilegeForPropertiesEditor", customPrivilegeValue.value.trim());
        } else {
            state.updateSettingsData("checkPrivilegeForPropertiesEditor", "125");
        }
    } else {
        useDefaultPrivilege.disabled = true;
        useCustomPrivilege.disabled = true;
        customPrivilegeValue.disabled = true;
        state.updateSettingsData("enablePrivilegeForEditor", "0");
        state.updateSettingsData("checkPrivilegeForPropertiesEditor", null);
    }
});

useDefaultPrivilege.addEventListener("change", (e) => {
    if (e.target.checked) {
        customPrivilegeValue.disabled = true;
        state.updateSettingsData("checkPrivilegeForPropertiesEditor", "125");
    }
});

useCustomPrivilege.addEventListener("change", (e) => {
    if (e.target.checked) {
        customPrivilegeValue.disabled = false;
    }
});

customPrivilegeValue.addEventListener("change", (e) => {
    if (e.target.value.trim() !== "") {
        state.updateSettingsData("checkPrivilegeForPropertiesEditor", e.target.value.trim());
    }
});

baseGridTheme.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    state.updateSettingsData("gridThemes.baseThemes", e.target.value);
});

chartAnimations.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    const value = e.target.checked ? "1" : "0";
    state.updateSettingsData("chart.animation", value);
});

linksAccess.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    const value = e.target.checked ? "1" : "0";
    state.updateSettingsData("security.allowURLLinks", value);
});

contextMenuAccess.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    const value = e.target.checked ? "1" : "0";
    state.updateSettingsData("statePresentation.contextMenu", value);
});

rtlSupport.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    const value = e.target.checked ? true : false;
    state.updateSettingsData("rtlSupport", value);
});

negativeValueFormat.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    state.updateSettingsData("metricNegativeValueFormat", e.target.value);
});

seriesColorsLimit.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    let value = e.target.value;
    if (Number(value) < Number(e.target.min)) {
        value = 50;
    }
    state.updateSettingsData("seriesLimit", value);
});

accessControlLevels.forEach((accessControlLevel) => {
    accessControlLevel.addEventListener("change", (e) => {
        state.setUnsavedChanges(true);
        const accessLevel = e.target.getAttribute("data-access-level");
        const activeControls = state.getSettingsData()["accessControlLevels"] || [];
        const hasFullControl = function() {
            const directFullControl = (e.target.checked) && (accessLevel === "fullcontrol");
            const indirectFullControl = activeControls.sort((a, b) => a.localeCompare(b)).join(",") === accessControlLevelCodes.join(",");
            return directFullControl || indirectFullControl;
        };

        if (e.target.checked && accessLevel !== "fullcontrol") {
            activeControls.push(accessLevel);
        }

        if (hasFullControl()) {
            accessControlLevels.forEach((level) => {
                level.checked = true;
            });
            activeControls.splice(0, activeControls.length, "fullcontrol");
        } else {
            // Empty accessControlLevels before filling it
            activeControls.splice(0, activeControls.length);

            if (accessLevel === "fullcontrol") {
                // Revoke all access levels if full control is unchecked
                accessControlLevels.forEach((level) => {
                    if (level.getAttribute("data-access-level") !== "fullcontrol") {
                        level.checked = false;
                    }
                });                
            } else {
                accessControlLevels.forEach((level) => {
                    if (level.getAttribute("data-access-level") === "fullcontrol") {
                        level.checked = false;
                    } else if (level.checked) {
                        activeControls.push(level.getAttribute("data-access-level"));
                    }
                });
            }
        }

        if (!activeControls.length) {
            state.updateSettingsData("accessControlLevels", null);
        } else {
            state.updateSettingsData("accessControlLevels", activeControls);
        }
    });
});

metricSuffixes.forEach((metricSuffix, index) => {
    metricSuffix.addEventListener("change", (e) => {
        const value = e.target.value.trim();
        if (value !== "") {
            state.setUnsavedChanges(true);
            metricSuffixValues[index] = value;
            state.updateSettingsData("shortFormatSymbols", metricSuffixValues);
        }
    });
});

ibcsByDefault.addEventListener("change", (e) => {
    state.setUnsavedChanges(true);
    state.updateIBCSSettingsData("UseIBCSAsDefaultViewMode", e.target.checked);
});

actualDataType.addEventListener("change", (e) => {
    const value = e.target.value.trim();
    if (value !== "") {
        state.setUnsavedChanges(true);
        state.updateIBCSSettingsData("DT.AC", value);
    }
});

forecastDataType.addEventListener("change", (e) => {
    const value = e.target.value.trim();
    if (value !== "") {
        state.setUnsavedChanges(true);
        state.updateIBCSSettingsData("DT.FC", value);
    }
});

plannedDataType.addEventListener("change", (e) => {
    const value = e.target.value.trim();
    if (value !== "") {
        state.setUnsavedChanges(true);
        state.updateIBCSSettingsData("DT.PL", value);
    }
});

previousDataType.addEventListener("change", (e) => {
    const value = e.target.value.trim();
    if (value !== "") {
        state.setUnsavedChanges(true);
        state.updateIBCSSettingsData("DT.PY", value);
    }
});

negativeMetrics.addEventListener("change", (e) => {
    const value = e.target.value.trim();
    if (value !== "") {
        state.setUnsavedChanges(true);
        state.updateIBCSSettingsData("negativeMetrics", value);
    }
});

export {
    chartAnimations,
    enablePrivilege,
    useDefaultPrivilege,
    useCustomPrivilege,
    customPrivilegeValue,
    baseGridTheme,
    linksAccess,
    contextMenuAccess,
    rtlSupport,
    negativeValueFormat,
    seriesColorsLimit,
    accessControlLevels,
    metricSuffixes,
    ibcsByDefault,
    actualDataType,
    forecastDataType,
    plannedDataType,
    previousDataType,
    negativeMetrics
};
