import { nextTick } from "vue";
import { createI18n } from "vue-i18n";
import { KcContextBase } from "~/types/context";

export const SUPPORT_LOCALES = ["en", "de"];

export function setupI18n(options = {}) {
  const browserLocale = navigator.language.split("-")[0];
  let defaultLocale = "en";
  if (SUPPORT_LOCALES.includes(browserLocale)) {
    defaultLocale = browserLocale;
  }

  const i18n = createI18n(options);
  setI18nLanguage(i18n, defaultLocale);
  return i18n;
}

export function setI18nLanguage(i18n, locale) {
  loadLocaleMessages(i18n, locale);
  if (i18n.mode === "legacy") {
    i18n.global.locale = locale;
  } else {
    i18n.global.locale.value = locale;
  }
}

export async function loadLocaleMessages(i18n, locale) {
  // load locale messages with dynamic import
  const context = (window as any).kcContext as KcContextBase.Common;
  const messages = await import(
    /* webpackIgnore: true */ `${context.url.resourcesPath}/locales/${locale}.js`
  );

  // set locale and locale message
  i18n.global.setLocaleMessage(locale, messages.content);

  return nextTick();
}
