import { useContext } from 'react';
import CommonContext from './CommonContext';
import { messageAction, silentLoadingAction, toastLoadingAction, } from './sessionTypes';
const translateErrorValue = (t, namespace, rawValue) => {
    const entry = `${namespace}:${rawValue}`;
    const translatedValue = t(entry);
    return translatedValue === entry ? rawValue : translatedValue;
};
export const getErrorMessageValue = ({ err, t, key }) => {
    if (!t) {
        return err;
    }
    if (!err.response) {
        return translateErrorValue(t, key ?? 'message', String(err));
    }
    if (err.response.status === 403) {
        return t('error.access.authorization');
    }
    let errorKey = '';
    if (err.response.data?.message) {
        errorKey = err.response.data.message;
    }
    else if (err.response.data?.description) {
        errorKey = err.response.data.description;
    }
    else if (err.response.data?.errors?.length > 0) {
        errorKey = err.response.data.errors[0].description;
    }
    else {
        key = 'common';
        errorKey = 'internal.server.error';
    }
    return translateErrorValue(t, key ?? 'message', errorKey);
};
export const useMessageUtils = () => {
    const { state, dispatch } = useContext(CommonContext);
    const isSilentLoading = () => {
        return state.silentLoading;
    };
    const dispatchSilent = (val) => {
        dispatch(silentLoadingAction(val));
    };
    const isLoading = () => {
        return state.toastLoading;
    };
    const dispatchLoading = (val, text) => {
        dispatch(text !== undefined
            ? toastLoadingAction({ loading: val, text })
            : toastLoadingAction(val));
    };
    const dispatchError = ({ err, t, key }) => {
        const value = getErrorMessageValue({ err, t, key });
        dispatch(messageAction({ value, type: 'error' }));
    };
    const dispatchMessage = ({ key, ns, t }) => {
        const entry = ns ? `${ns}:${key}` : `message:${key}`;
        dispatch(messageAction({ value: t(entry), type: 'success' }));
    };
    const dispatchMessageDirect = (value, type = 'success') => {
        dispatch(messageAction({ value, type }));
    };
    return {
        dispatchLoading,
        dispatchError,
        dispatchMessage,
        dispatchMessageDirect,
        isLoading,
        dispatchSilent,
        isSilentLoading,
    };
};
