<script setup>
import { onMounted } from 'vue';
import axios from 'axios';
import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useSession } from 'src/composables/useSession';

const quasar = useQuasar();
const router = useRouter();
const session = useSession();
const { t, availableLocales, locale, fallbackLocale } = useI18n();
const { isLoggedIn } = session;

onMounted(() => {
    let userLang = window.navigator.language;
    if (userLang.includes('-')) {
        userLang = userLang.split('-')[0];
    }

    if (availableLocales.includes(userLang)) {
        locale.value = userLang;
    } else {
        locale.value = fallbackLocale;
    }
});

quasar.iconMapFn = (iconName) => {
    if (iconName.startsWith('vn:')) {
        const name = iconName.substring(3);

        return {
            cls: `icon-${name} notranslate`,
        };
    }

    return {
        cls: 'material-symbols-outlined notranslate',
        content: iconName,
    };
};

function responseError(error) {
    let message = error.message;
    let logOut = false;

    switch (error.response?.status) {
        case 401:
            message = 'login.loginError';

            if (isLoggedIn()) {
                message = 'errors.statusUnauthorized';
                logOut = true;
            }
            break;
        case 403:
            message = 'errors.statusUnauthorized';
            break;
        case 500:
            message = 'errors.statusInternalServerError';
            break;
        case 502:
            message = 'errors.statusBadGateway';
            break;
        case 504:
            message = 'errors.statusGatewayTimeout';
            break;
    }

    let translatedMessage = t(message);
    if (!translatedMessage) translatedMessage = message;

    quasar.notify({
        message: translatedMessage,
        type: 'negative',
    });

    if (logOut) {
        session.destroy();
        router.push({ path: '/login' });
    }

    return Promise.reject(error);
}

axios.interceptors.response.use((response) => {
    const { method } = response.config;

    const isSaveRequest = method === 'patch';
    if (isSaveRequest) {
        quasar.notify({
            message: t('globals.dataSaved'),
            type: 'positive',
            icon: 'check',
        });
    }
    return response;
}, responseError);
</script>

<template>
    <router-view />
</template>

<style lang="scss">
.body--light {
    background-color: #eee;
}
</style>
