import { postJson } from "./Request.js";
import { notiConfirm } from "./Notiflix.js";
import { customLang } from "./AdminConfigure.js";

const vectorMap = () => {
    jsonCountriesFileExist("countries.json", function (isFileChecked) {
        if (isFileChecked) {
            postJson("countries.json").then((result) => {
                initializeMap(result);
            });
        } else {
            const result = [
                {
                    values: {},
                },
            ];
            initializeMap(result);
        }
    });
};

const vectorMapAdmin = () => {
    jsonCountriesFileExist("countries.json", function (isFileChecked) {
        if (isFileChecked) {
            postJson("countries.json").then((result) => {
                initializeMap(result, true);
            });
        } else {
            const result = [
                {
                    values: {},
                },
            ];
            initializeMap(result, true);
        }
    });
};

const vectorMapChanged = (process, code) => {
    postJson("api/Countries", {
        process,
        code,
    }).then(() => {
        window.location.reload();
    });
};

function jsonCountriesFileExist(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    JSON.parse(xhr.responseText);
                    callback(true);
                } catch (error) {
                    callback(false);
                }
            } else {
                callback(false);
            }
        }
    };
    xhr.send();
}

function initializeMap(result, adminMode = false) {
    let initialFillColor = "";
    let selectedFillColor = "";
    const themeMode = document.querySelector("body");

    const updateMapColors = () => {
        if (themeMode.classList.contains("theme-dark")) {
            initialFillColor = "#B9B7B7";
            selectedFillColor = "gray";
        } else {
            initialFillColor = "#505050";
            selectedFillColor = "gray";
        }

        const mapContainer = document.getElementById("world-map");
        if (mapContainer) {
            $(mapContainer).empty();
            $(mapContainer).vectorMap({
                map: "world_mill_en",
                zoomOnScroll: adminMode,
                zoomButtons: adminMode,
                series: {
                    regions: [
                        {
                            ...result[0],
                            attribute: "fill",
                        },
                    ],
                },
                regionStyle: {
                    initial: {
                        fill: initialFillColor,
                    },
                    selected: {
                        fill: selectedFillColor,
                    },
                },
                regionsSelectable: adminMode,
                regionsSelectableOne: adminMode,
                onRegionClick: async function (event, code) {
                    const langGet = await customLang("admin", "index");
                    const lang = langGet.vectorLang;
                    const countries = result[0].values;
                    const isKeyPresent = code in countries;
                    let title = "";
                    let message = "";
                    let buttonOkText = "";
                    let buttonCanceledText = "";
                    let okButtonBackground = "";
                    let process = "";
                    if (isKeyPresent) {
                        title = lang.Positive.title;
                        message = lang.Positive.message;
                        buttonOkText = lang.Positive.buttonOkText;
                        buttonCanceledText = lang.Positive.buttonCanceledText;
                        okButtonBackground = "#d01717";
                        process = "remove";
                    } else {
                        title = lang.Negative.title;
                        message = lang.Negative.message;
                        buttonOkText = lang.Negative.buttonOkText;
                        buttonCanceledText = lang.Negative.buttonCanceledText;
                        okButtonBackground = "#32c682";
                        process = "add";
                    }

                    notiConfirm(
                        title,
                        message,
                        buttonOkText,
                        buttonCanceledText,
                        vectorMapChanged,
                        process,
                        code,
                        {
                            position: "center",
                            distance: "10px",
                            backgroundColor: "#f8f8f8",
                            borderRadius: "25px",
                            backOverlay: true,
                            backOverlayColor: "rgba(0,0,0,0.5)",
                            cssAnimation: true,
                            cssAnimationDuration: 300,
                            cssAnimationStyle: "fade",
                            plainText: true,
                            titleColor: "#32c682",
                            titleFontSize: "22px",
                            titleMaxLength: 34,
                            messageColor: "#1e1e1e",
                            messageFontSize: "18px",
                            messageMaxLength: 500,
                            buttonsFontSize: "15px",
                            buttonsMaxLength: 34,
                            okButtonColor: "#f8f8f8",
                            okButtonBackground: `${okButtonBackground}`,
                            cancelButtonColor: "#f8f8f8",
                            cancelButtonBackground: "#a9a9a9",
                        }
                    );
                },
            });
        }
    };
    updateMapColors();
    const observer = new MutationObserver((mutationsList, observer) => {
        for (const mutation of mutationsList) {
            if (mutation.type === "attributes" && mutation.attributeName === "class") {
                updateMapColors();
                break;
            }
        }
    });
    observer.observe(themeMode, { attributes: true });
    const cleanup = () => {
        observer.disconnect();
    };
    window.addEventListener("beforeunload", cleanup);
    window.addEventListener("unload", cleanup);
}

export { vectorMap, vectorMapAdmin };
