import wccRest from "@/helpers/api";
import store from '@/store/store';
import { getOption, purgeCache } from "@/helpers/common";

const languages = {

    /**
     * Get all the available languages
     *
     * @since 3.0.0
     *
     * @return {array}
     */
    get: async function () {
        try {
            const languages = await wccRest.get({ path: "languages/available" });
            return languages;
        } catch (error) {
            console.error(error);
            return [];
        }
    },

    /**
     * Get language details from array of language codes
     *
     * @since 3.0.0
     *
     * @return {array}
     */
    getLanguageDetails: function (availableLangs, selectedLangs) {
        let languageDetails = availableLangs.filter(function (lang) {
            if (selectedLangs.indexOf(lang.code) != -1) {
                return lang;
            }
        });
        return languageDetails;
    },
    getName(code) {
        let language = store.state.languages.available.find(function (lang) {
            return lang.code == code;
        });
        return typeof language !== "undefined" ? language.name : '';
    },
    deleteLanguage: async function (code) {
        if (code) {
            let languages = getOption('languages');
            let index = languages.selected.indexOf(code);
            if (index !== -1) {
                languages.selected.splice(index, 1);
            }
            store.dispatch("languages/setSelected", languages.selected);
            await store.dispatch("languages/saveSelected");
            await purgeCache();
            await store.dispatch("banners/reInit");
            await store.dispatch("cookies/reInit");
            return true;
        }
    },
    getTranslatedLanguages() {
        return [
            'bg',
            'ca',
            'cs',
            'da',
            'de',
            'el',
            'en',
            'es',
            'eu',
            'fi',
            'fr',
            'hu',
            'it',
            'lt',
            'nl',
            'pl',
            'pt-br',
            'pt',
            'sk',
            'sv',
            'ro',
            'tr'
        ];
    },
    deepEqual(object1, object2) {
        const keys1 = Object.keys(object1);
        const keys2 = Object.keys(object2);
        if (keys1.length !== keys2.length) {
            return false;
        }
        for (const key of keys1) {
            const val1 = object1[key];
            const val2 = object2[key];
            const areObjects = this.isObject(val1) && this.isObject(val2);
            if (
                areObjects && !this.deepEqual(val1, val2) ||
                !areObjects && val1 !== val2
            ) {
                return false;
            }
        }
        return true;
    },
    isObject(object) {
        return object != null && typeof object === 'object';
    }
}
export default languages;