import { log } from "../_utils/log.mjs";
import { isString, isUndefined, isArray } from "../_utils/is.mjs";
import "../config-provider/index.mjs";
import { ref, getCurrentInstance, inject, computed } from "vue";
import zhCN from "./lang/zh-cn.mjs";
import { configProviderInjectKey } from "../config-provider/provide.mjs";
const currentLocal = ref("zh-CN");
const i18nLanguage = ref({
  "zh-CN": zhCN
});
function addLocale(locale, opts) {
  const locales = isArray(locale) ? locale : [locale];
  locales.forEach((lc) => {
    const currLocal = lc.locale;
    if (!currLocal) {
      return;
    }
    if (!i18nLanguage.value[currLocal]) {
      i18nLanguage.value[currLocal] = {
        locale: lc.locale
      };
    }
    Object.keys(lc).forEach((key) => {
      const k = key;
      if (!i18nLanguage.value[currLocal][k] || (opts == null ? void 0 : opts.overwrite)) {
        i18nLanguage.value[currLocal][k] = lc[key];
      }
    });
  });
}
function useLocale(localeKey) {
  if (!i18nLanguage.value[localeKey]) {
    log.warn(`no '${localeKey}' languages configed`);
    return;
  }
  currentLocal.value = localeKey;
}
function useI18n() {
  const instance = getCurrentInstance();
  const configProvider = instance ? inject(configProviderInjectKey, {}) : null;
  const languages = computed(() => {
    return (configProvider == null ? void 0 : configProvider.locale) ?? i18nLanguage.value[currentLocal.value];
  });
  const locale = computed(() => languages.value.locale);
  const transform = (key, ...args) => {
    if (!languages.value) {
      log.warn("no languages configed");
      return "";
    }
    const value = languages.value[key];
    if (args.length > 0 && isString(value)) {
      return value.replace(/{(\d+)}/g, (match, index) => {
        return args[index] ?? match;
      });
    }
    if (isUndefined(value)) {
      log.warn(`Cannot translate the value of keypath '${key}'`);
    }
    return value;
  };
  return {
    locale,
    t: transform
  };
}
export {
  addLocale,
  useI18n,
  useLocale
};
