import { useMemo, useCallback, createElement, Fragment } from "react";
import { DictionaryCache } from "./DictionaryCache.js";
import { I18nError } from "./I18nError.js";
import { useI18n } from "./useI18n.js";
const assignKeys = (chunks) => {
  if (!Array.isArray(chunks)) {
    chunks = [chunks];
  }
  return createElement(Fragment, {
    children: chunks.map((chunk, index) => createElement(Fragment, {
      key: index,
      children: chunk
    }))
  });
};
const hasFunctionValue = (object) => {
  for (const key in object) {
    if (typeof object[key] === "function") {
      return true;
    }
  }
  return false;
};
const formatMessage = (i18n, fallback, key, values) => {
  let message;
  try {
    message = i18n.dictionaryResolver.getMessageFormat(i18n.locale, key, fallback);
  } catch (e) {
    const original = i18n.dictionaryResolver.getResolvedMessageForDebuggingPurposes(i18n.locale, key, fallback);
    throw new I18nError(`Failed to format key '${key}'.${original ? ` It resolved to
${original}` : ""}

${e.message}`);
  }
  if (message === void 0) {
    throw new I18nError(`Cannot translate the message '${key}'. It's neither in the resolved nor the fallback dictionary.`);
  }
  if (values && hasFunctionValue(values)) {
    values = Object.fromEntries(Object.entries(values).map(([key2, value]) => {
      if (typeof value === "function") {
        return [key2, (chunks) => value(assignKeys(chunks))];
      }
      return [key2, value];
    }));
  }
  try {
    let formatted = message.format(values);
    if (typeof formatted === "string") {
      return formatted;
    }
    return assignKeys(formatted);
  } catch (e) {
    const original = i18n.dictionaryResolver.getResolvedMessageForDebuggingPurposes(i18n.locale, key, fallback);
    throw new I18nError(`Failed to format key '${key}'. It resolved to
${original}

${e.message}`);
  }
};
const useMessageFormatter = (defaultDictionary) => {
  const i18n = useI18n();
  const fallbackDictionaryCache = useMemo(() => new DictionaryCache(defaultDictionary), [defaultDictionary]);
  return useCallback((...args) => {
    if (args.length === 1 || args.length === 2 && typeof args[1] !== "string") {
      const [key, values] = args;
      return formatMessage(i18n, fallbackDictionaryCache, key, values);
    } else {
      const [userSpecifiedKey, fallbackKey, values] = args;
      if (userSpecifiedKey !== void 0) {
        if (typeof userSpecifiedKey === "string") {
          const message = i18n.dictionaryResolver.getMessageFormat(i18n.locale, userSpecifiedKey, fallbackDictionaryCache);
          if (message === void 0) {
            return userSpecifiedKey;
          }
          return message.format(values);
        }
        return userSpecifiedKey;
      }
      return formatMessage(i18n, fallbackDictionaryCache, fallbackKey, values);
    }
  }, [fallbackDictionaryCache, i18n]);
};
export { useMessageFormatter };
//# sourceMappingURL=useMessageFormatter.js.map
