import axios from 'axios';
import { boot } from 'quasar/wrappers';
import qFormMixin from './qformMixin';
import keyShortcut from './keyShortcut';
import { QForm } from 'quasar';
import { QLayout } from 'quasar';
import mainShortcutMixin from './mainShortcutMixin';
import { useCau } from 'src/composables/useCau';

export default boot(({ app }) => {
    QForm.mixins = [qFormMixin];
    QLayout.mixins = [mainShortcutMixin];

    app.directive('shortcut', keyShortcut);
    app.config.errorHandler = async (error) => {
        let message;
        const response = error.response;
        const responseData = response?.data;
        const responseError = responseData && response.data.error;
        if (responseError) {
            message = responseError.message;
        }

        switch (response?.status) {
            case 422:
                if (error.name == 'ValidationError')
                    message +=
                        ' "' +
                        responseError.details.context +
                        '.' +
                        Object.keys(responseError.details.codes).join(',') +
                        '"';
                break;
            case 500:
                message = 'errors.statusInternalServerError';
                break;
            case 502:
                message = 'errors.statusBadGateway';
                break;
            case 504:
                message = 'errors.statusGatewayTimeout';
                break;
        }

        console.error(error);
        if (error instanceof axios.CanceledError) {
            const env = process.env.NODE_ENV;
            if (env && env !== 'development') return;
            message = 'Duplicate request';
        }

        await useCau(response, message);
    };
});
