/**
 * Program: i18n
 * Author: SDL
 * Description: i18n language setting file
 */
// https://kazupon.github.io/vue-i18n/guide/lazy-loading.html
import { createI18n } from 'vue-i18n';
import axios from 'axios';
import isEmpty from 'lodash/isEmpty';
import store from '@/vuex/store';
import SDLUtil from '@/utils/SDLUtil';

const defaultLanguage = (window.navigator.language || SDLUtil.DEFAULT_LANG).replace('-', '_');

export const i18n = createI18n({
  locale: defaultLanguage, // set locale
  fallbackLocale: {
    'ko': ['ko_KR'],
    'en': ['en_US'],
    'default': ['en_US'],
  }, // fallback lang
  messages: {}, // set locale messages
  silentFallbackWarn: true,
  silentTranslationWarn: true,
  warnHtmlInMessage: 'off', // disable of the Detected HTML in message
});

let loadedLanguages = []; // our default language that is preloaded

function setI18nLanguage(lang) {
  i18n.global.locale = lang;
  store.commit('LOCALE', lang);
  axios.defaults.headers.common['Accept-Language'] = lang;
  document.querySelector('html').setAttribute('lang', lang);
  return lang;
}

export async function loadLanguageAsync(lang) {
  let language;
  if (isEmpty(loadedLanguages)) {
    await axios.get(`${SDLUtil.API_URL}/noauth/messages/all`).then(msgs => {
      loadedLanguages = Object.keys(msgs.data);
      loadedLanguages.forEach(country => {
        i18n.global.setLocaleMessage(country, msgs.data[country]);
      });
    });
  }
  try {
    language = loadedLanguages.find(find => find === lang) || loadedLanguages.find(find => find.includes(lang.split('_')[0])) || SDLUtil.DEFAULT_LANG;
  } catch (e) {
    language = SDLUtil.DEFAULT_LANG;
  }
  return setI18nLanguage(language);
}

export default i18n;
