import axios from 'axios';

export function initialize(store, router) {
    router.beforeEach((to, from, next) => {
        window.document.title = to.meta.pageTitle !== undefined ? to.meta.pageTitle : '';
        store.state.dataList = {};
        store.state.detailsData = {};
        store.state.formObject = {};
        store.state.formType = 1;
        store.state.updateId = '';
        $('body').removeClass('vertical-sidebar-enable');

        store.formFilter = {
            keyword : '',
            perPage : 15,
            status : '',
        };

        next();
    });


    if (localStorage.getItem('software')){
        store.state.software = localStorage.getItem('software');
        axios.defaults.headers.common['Software'] = localStorage.getItem('software');
    }


    axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

    axios.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        if (parseInt(error.response.status) === 401){
            // store.commit('logout');
        }
        return Promise.reject(error);
    });

    const initialTheme = localStorage.getItem('theme_mode') || 'light';
    applyThemeMode(initialTheme);
}

export function applyThemeMode(mode) {
    let activeTheme = mode;
    if (!activeTheme || activeTheme === 'system') {
        const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        activeTheme = prefersDark ? 'dark' : 'light';
    }

    const html = document.documentElement;
    const body = document.body;

    if (activeTheme === 'dark') {
        html.setAttribute('data-layout-mode', 'dark');
        html.setAttribute('data-topbar', 'dark');
        html.setAttribute('data-sidebar', 'dark');
        html.setAttribute('data-theme', 'dark');
        html.classList.add('dark-mode');
        html.classList.remove('light-mode');
        if (body) {
            body.classList.add('dark-theme');
            body.classList.remove('light-theme');
        }
    } else {
        html.setAttribute('data-layout-mode', 'light');
        html.setAttribute('data-topbar', 'light');
        html.setAttribute('data-sidebar', 'dark');
        html.setAttribute('data-theme', 'light');
        html.classList.add('light-mode');
        html.classList.remove('dark-mode');
        if (body) {
            body.classList.add('light-theme');
            body.classList.remove('dark-theme');
        }
    }
}

