import { createStore } from "@stencil/store";
import { useTranslation } from "../utils/utils";
import { AxiosError } from "axios";
const { state } = createStore({
    dialog: { open: false, type: "DEFAULT" /* DIALOG_TYPE.DEFAULT */ },
});
export const dialogStore = state;
export const openDialog = (dialog) => {
    state.dialog = { ...dialog, open: true };
};
export const closeDialog = (callback) => {
    state.dialog = { open: false, type: "DEFAULT" /* DIALOG_TYPE.DEFAULT */ };
    if (callback)
        callback();
};
export const handleError = (error, defaultMessage = 'error') => {
    const t = useTranslation();
    let title = defaultMessage;
    let contentCustom = null;
    if (error instanceof Error && error.name === 'RateLimitError') {
        // eslint-disable-next-line no-console
        console.warn(error.message);
        return;
    }
    if (error instanceof AxiosError) {
        if (error.response && error.response.data) {
            const response = error.response.data;
            const code = response ? response.code : '';
            const message = response ? response.message : '';
            if (code === 'RATE_LIMIT_EXCEEDED') {
                return;
            }
            if (['user-status-already-exists', 'user-tag-already-exists'].includes(code || '')) {
                contentCustom = t(code);
            }
            else if (message) {
                contentCustom = message;
            }
        }
        else if (error.message) {
            title = error.message;
        }
        // eslint-disable-next-line no-console
        console.error(defaultMessage, error);
    }
    else if (error instanceof Error) {
        title = error.message;
        // eslint-disable-next-line no-console
        console.error(defaultMessage, error);
    }
    else {
        // eslint-disable-next-line no-console
        console.error(defaultMessage, error);
    }
    openDialog({
        open: true,
        type: "ERROR" /* DIALOG_TYPE.ERROR */,
        title: t(title),
        contentCustom,
        onCloseDialog: closeDialog,
    });
};
