// source --> https://www.seegutsteeg.at/wp-content/plugins/my-bookings-res/resources/scripts/MyBookingsRES.js?ver=7.0 
class MyBookingsRES {
    adminPageVueInstance;
    categoryListVueInstance;
    filterVueInstance;

    url;

    setAdminPageVueInstance(vueInstance) {
        this.adminPageVueInstance = vueInstance;
    }

    setCategoryListVueInstance(vueInstance) {
        this.categoryListVueInstance = vueInstance;
    }

    setFilterVueInstance(vueInstance) {
        this.filterVueInstance = vueInstance;
    }

    performAvailabilityCheck() {
        if (!this.categoryListVueInstance) {
            return;
        }

        this.categoryListVueInstance.performAvailabilityCheck();
    }

    webRequest(controllerFunctionName, requestParameters = {}) {
        const requestData = new FormData();
        requestData.append(
            "action",
            phpVariables.pluginPrefix + controllerFunctionName
        );

        for (const [key, value] of Object.entries(requestParameters)) {
            requestData.append(key, value);
        }

        return new Promise((resolve) => {
            axios.post(phpVariables.url, requestData).then(
                (data) => {
                    resolve(data.data);
                },
                (error) => {
                    resolve({
                        payload: null,
                        error: error.message,
                        statusCode: error.response.status,
                    });
                }
            );
        });
    }

    goToPage(
        baseUrl,
        parameters = {},
        strict = false,
        onlyUpdateParameters = false
    ) {
        const url = new URL(baseUrl);

        if (strict) {
            const searchParameters = new URLSearchParams(url.searchParams);

            searchParameters.forEach((parameterKey) => {
                url.searchParams.delete(parameterKey);
            });
        }

        for (const [parameterKey, parameterValue] of Object.entries(parameters)) {
            url.searchParams.set(parameterKey, parameterValue);
        }

        if (parameters.hasOwnProperty("mbc") && parameters.mbc === "0") {
            url.searchParams.delete("mbca");
        }

        if (onlyUpdateParameters) {
            window.history.pushState({}, "", url.href);
        } else {
            location.href = url.href;
        }
    }

    getUrl(baseUrl, parameters = {}, strict = false) {
        const url = new URL(baseUrl);

        if (strict) {
            const searchParameters = new URLSearchParams(url.searchParams);

            searchParameters.forEach((parameterKey) => {
                url.searchParams.delete(parameterKey);
            });
        }

        for (const [parameterKey, parameterValue] of Object.entries(parameters)) {
            url.searchParams.set(parameterKey, parameterValue);
        }

        return url.href;
    }

    getUrlParameter(key) {
        const url = new URL(window.location);

        return url.searchParams.get(key);
    }

    getUrlParameters(url = null) {
        if (!this.url) {
            this.url = new URL(url || window.location);
        }

        const parameters = {};
        this.url.searchParams.forEach((parameterValue, parameterKey) => {
            parameters[parameterKey] = parameterValue;
        });

        return parameters;
    }

    notifySuccess(message) {
        if (!this.adminPageVueInstance) {
            return;
        }

        this.adminPageVueInstance.addSuccessToastMessage(message);
    }

    notifyError(message) {
        if (!this.adminPageVueInstance) {
            return;
        }

        this.adminPageVueInstance.addErrorToastMessage(message);
    }

    formatDate(dateString) {
        const date = new Date(dateString);

        return [
            date.getDate().toString().padStart(2, "0"),
            (date.getMonth() + 1).toString().padStart(2, "0"),
            date.getFullYear(),
        ].join(".");
    }

    formatDateTime(dateString) {
        const date = new Date(dateString);

        const time = [
            date.getHours().toString().padStart(2, "0"),
            date.getMinutes().toString().padStart(2, "0"),
        ].join(":");

        return [this.formatDate(dateString), time].join(" ");
    }

    getAccommodationDemonstrativeNominative(typeCode) {
        if (phpVariables && phpVariables.lang !== "de") {
            return "";
        }
        if (typeCode === "U") {
            return "Diese";
        }
        return "Dieses";
    }

    // Simple Vue I18n-like pluralization using pipe-separated forms in translation values
    // Example per language: "U_noun": "Unterkunft|Unterkünfte"
    ___plural(key, count, vars = {}) {
        const currentLanguage = phpVariables.lang;
        const translations = phpVariables.translations;

        if (!translations || !translations.hasOwnProperty(key)) {
            return key;
        }

        const phraseTranslations = translations[key];
        let raw = "";

        if (
            phraseTranslations.hasOwnProperty(currentLanguage) &&
            phraseTranslations[currentLanguage] !== ""
        ) {
            raw = phraseTranslations[currentLanguage];
        } else if (
            phraseTranslations.hasOwnProperty("en") &&
            phraseTranslations["en"] !== ""
        ) {
            raw = phraseTranslations["en"];
        } else {
            return key;
        }

        const forms = raw.split("|").map((s) => s.trim());
        let index = 0;
        if (forms.length >= 2) {
            index = count === 1 ? 0 : 1;
        }

        let result = forms[Math.min(index, forms.length - 1)] || "";
        const allVars = {...vars, count};
        result = result.replace(/{{\s*(\w+)\s*}}/g, (_, key) => allVars[key] || "");
        return result;
    }

    ___(phrase, addTranslationCallback, vars = {}) {
        const currentLanguage = phpVariables.lang;
        const translations = phpVariables.translations;

        if (!translations || !translations.hasOwnProperty(phrase)) {
            addTranslationCallback();
            return phrase;
        }

        const phraseTranslations = translations[phrase];
        let translatedPhrase = "";

        if (
            phraseTranslations.hasOwnProperty(currentLanguage) &&
            phraseTranslations[currentLanguage] !== ""
        ) {
            translatedPhrase = phraseTranslations[currentLanguage];
        } else if (
            phraseTranslations.hasOwnProperty("en") &&
            phraseTranslations["en"] !== ""
        ) {
            translatedPhrase = phraseTranslations["en"];
        } else {
            return phrase;
        }

        translatedPhrase = translatedPhrase.replace(
            /{{\s*(\w+)\s*}}/g,
            (_, key) => vars[key] || ""
        );

        return translatedPhrase;
    }

    ___frontEnd(phrase, vars = {}) {
        return myBookingsRES.___(
            phrase,
            () => {
                myBookingsRES.addTranslationFrontEnd(phrase);
            },
            vars
        );
    }

    ___backEnd(phrase, vars = {}) {
        return myBookingsRES.___(
            phrase,
            () => {
                myBookingsRES.addTranslationBackEnd(phrase);
            },
            vars
        );
    }

    addTranslationFrontEnd(phrase) {
        this.webRequest("addTranslationFrontEnd", {phrase});
    }

    addTranslationBackEnd(phrase) {
        this.webRequest("addTranslationBackEnd", {phrase});
    }

    getFrontendMixin() {
        return {
            methods: {
                webRequest: this.webRequest,
                formatDate: this.formatDate,
                formatDateTime: this.formatDateTime,
                getAccommodationDemonstrativeNominative:
                this.getAccommodationDemonstrativeNominative,
                notifySuccess: this.notifySuccess,
                notifyError: this.notifyError,
                getUrlParameter: this.getUrlParameter,
                getUrlParameters: this.getUrlParameters,
                getUrl: this.getUrl,
                goToPage: this.goToPage,
                ___: this.___frontEnd,
                ___plural: this.___plural,
            },
        };
    }

    getBackendMixin() {
        return {
            methods: {
                webRequest: this.webRequest,
                formatDate: this.formatDate,
                formatDateTime: this.formatDateTime,
                getAccommodationDemonstrativeNominative:
                this.getAccommodationDemonstrativeNominative,
                notifySuccess: this.notifySuccess,
                notifyError: this.notifyError,
                getUrlParameter: this.getUrlParameter,
                getUrlParameters: this.getUrlParameters,
                getUrl: this.getUrl,
                goToPage: this.goToPage,
                ___: this.___backEnd,
                ___plural: this.___plural,
            },
        };
    }
}

const myBookingsRES = new MyBookingsRES();