import { boot } from 'quasar/wrappers';
import qFormMixin from './qformMixin';
import keyShortcut from './keyShortcut';
import useNotify from 'src/composables/useNotify.js';
import { CanceledError } from 'axios';

const { notify } = useNotify();

export default boot(({ app }) => {
    app.mixin(qFormMixin);
    app.directive('shortcut', keyShortcut);
    app.config.errorHandler = (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 CanceledError) {
            const env = process.env.NODE_ENV;
            if (env && env !== 'development') return;
            message = 'Duplicate request';
        }

        notify(message ?? 'globals.error', 'negative', 'error');
    };
});
