import { useEffect, useCallback, useMemo } from "react";
import { createSimpleContext } from "../simple";
import { useFetch } from "../../hooks/common";
const URL = "https://content.equilibrium.io/error-messages";
const predicate = (body) => Array.isArray(body) &&
    ((body.length > 0 && "id" in body[0] && "message" in body[0]) ||
        body.length === 0);
const prepareStr = (s) => s.replace(/\s/g, "").toLowerCase();
const Context = createSimpleContext("error-decoder", () => {
    throw new Error("decode not initialized");
}, () => {
    const fetch = useFetch({
        query: URL,
        parsePayload: (raw) => JSON.parse(raw),
        predicate,
    }, false);
    useEffect(() => {
        fetch.exec();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    const messages = useMemo(() => {
        if (!fetch.data)
            return [];
        return fetch.data;
    }, [fetch.data]);
    const decode = useCallback((errorMessage, lang = "en") => {
        const key = prepareStr(errorMessage);
        const decoded = messages.find(({ error }) => prepareStr(error) === key);
        if (!decoded?.message)
            return errorMessage;
        return decoded[`message_${lang}`] ?? decoded.message;
    }, [messages]);
    return decode;
});
export const ErrorDecoderProvider = Context.Provider;
export const useErrorDecoder = Context.useContext;
//# sourceMappingURL=error-decoder.js.map