import wccRest from "@/helpers/api";
import { setDefaultLanguage, checkDomain } from "@/helpers/common";

const settings = {
    namespaced: true,
    state: {
        options: window.wccConfig.settings,
        info: false,
        status: true,
        errors: {},
    },

    getters: {
        /**
         * Get the all settings object.
         *
         * @param {object} state Current state.
         *
         * @return {*}
         */
        get: (state) => {
            return state.options
        },
        getInfo: (state) => {
            return state.info
        },

    },

    mutations: {
        /**
         * Update a single value in store.
         *
         * Updates the value only on store.
         * Call update mutation to store the values in db.
         *
         * @param {object} state Current state.
         * @param {object} data Data to update.
         */
        set: (state, data) => {
            if (Object.prototype.hasOwnProperty.call(state.options, data.key)) {
                state.options[data.key] = data.value
            }
        },
        setInfo: (state, data) => {
            state.info = data;
        },

        /**
         * Update the whole settings data in state.
         *
         * This will replace the current state with the
         * data provided.
         *
         * @param {object} state Current state.
         * @param {object} data Custom params.
         */
        update: (state, data) => {
            window.wccConfig.settings = data
            state.options = data
        },
        updateStatus: (state, status = true) => {
            state.status = status
        },
        setErrors: (state, errors) => {
            state.errors = errors
        }

    },

    actions: {
        /**
         * Re-initialize the settings store forcefully.
         *
         * We need to call the API and get the settings,
         * then update the store state with the new values.
         *
         * @param commit Commit
         * @param {object} data Custom params.
         *
         * @return {Promise<void>}
         */
        reInit: async ({ commit }) => {
            await wccRest
                .get({
                    path: "settings",
                })
                .then((response) => {
                    if (response.account) {
                        commit('update', response)
                    }
                });
        },
        loadInfo: async ({ commit, state, dispatch }, force = false) => {
            let status = false;
            status = true;
            await wccRest
                .get({
                    path: "settings/info",
                    params: { 'force': force },
                })
                .then((response) => {
                    if (response) {
                        commit('setInfo', response)
                        commit('updateStatus', true)
                        const languages = state.info && state.info.languages ? state.info.languages : [];
                        const defaultLang = languages && languages.default ? languages.default : 'en';
                        setDefaultLanguage(defaultLang);
                        dispatch('checkURLMismatch');
                    }
                }).catch(async (error) => {
                    if (error && error.data && error.data.status) {
                        commit('updateStatus', false)
                    }
                });
            return status;
        },
        /**
         * Set a single option value after validation.
         *
         * Make sure all required settings are provided, then
         * call the mutation.
         *
         * @param commit Commit.
         * @param {object} data Custom params.
         */
        set: ({ commit }, data = {}) => {
            // Only if all required settings are found.
            if (
                data['key'] && data['value']
            ) {
                commit('set', data)
            }
        },

        /**
         * Set a single option value after validation.
         *
         * Make sure all required settings are provided, then
         * call the mutation.
         *
         * @param commit Commit.
         * @param {object} data Custom params.
         */
        setInfo: ({ commit }, data = {}) => {
            // Only if all required settings are found.
            if (
                data['key'] && data['value']
            ) {
                commit('setInfo', data)
            }
        },

        /**
         * Update the settings values in db.
         *
         * Use the API and update the whole values.
         * Only do this when required.
         *
         * @param {object} Commit and State.
         * @param {object} data Custom params.
         *
         * @return {boolean}
         */
        save: async ({ commit, state, dispatch }) => {
            const value = state.options;
            let success = false;
            await wccRest
                .post({
                    path: "settings",
                    data: value
                })
                .then((response) => {
                    if (response) {
                        commit('update', response)
                        dispatch('loadInfo'); // Refresh info.
                        success = true
                    }
                });
            return success
        },
        checkURLMismatch({ state, commit }) {

            if (state.options.account.connected === false) return;
            if (!checkDomain()) {
                let errors = {};
                errors["urlMismatch"] = true;
                commit('setErrors', errors);
            }
        }
    },

}
export default settings