import type { AvailableLanguages } from "@/stores/user";
import dayjs from "dayjs";
import { nextTick } from "vue";
import { createI18n } from "vue-i18n";

// https://vue-i18n.intlify.dev/guide/advanced/lazy.html
export const SUPPORT_LOCALES: AvailableLanguages[] = ["de", "fr", "it"];
let i18n: any = null;

export function setupI18n(
  options = { locale: "de", legacy: false, fallbackLocale: "de" }
) {
  i18n = createI18n(options);
  setI18nLanguage(options.locale);
  dayjs.locale(options.locale);
  return i18n;
}

export function setI18nLanguage(locale: string) {
  if (i18n.mode === "legacy") {
    i18n.global.locale = locale;
  } else {
    i18n.global.locale.value = locale;
  }
  /**
   * NOTE:
   * If you need to specify the language setting for headers, such as the `fetch` API, set it here.
   * The following is an example for axios.
   *
   * axios.defaults.headers.common['Accept-Language'] = locale
   */
  document.querySelector("html")?.setAttribute("lang", locale);
}

export async function loadLocaleMessages(locale: any) {
  // load locale messages with dynamic import
  const messages = await import(
    /* webpackChunkName: "locale-[request]" */ `./locales/${locale}.json`
  );

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

  return nextTick();
}
