import Vue from 'vue'
import VueI18n from 'vue-i18n'
import elementLocale from 'element-ui/lib/locale'
import zhCN from './zh-CN'
import enUS from './en-US'

Vue.use(VueI18n)

export const DEFAULT_LOCALE = 'en-US'
export const LOCALE_STORAGE_KEY = 'language'
export const SUPPORT_LOCALES = ['zh-CN', 'en-US']

function getSavedLocale() {
  const savedLocale = localStorage.getItem(LOCALE_STORAGE_KEY)
  return SUPPORT_LOCALES.indexOf(savedLocale) > -1 ? savedLocale : DEFAULT_LOCALE
}

const i18n = new VueI18n({
  locale: getSavedLocale(),
  fallbackLocale: DEFAULT_LOCALE,
  silentTranslationWarn: true,
  messages: {
    'zh-CN': zhCN,
    'en-US': enUS
  }
})

elementLocale.i18n((key, value) => i18n.t(key, value))

export function setLocale(locale) {
  const nextLocale = SUPPORT_LOCALES.indexOf(locale) > -1 ? locale : DEFAULT_LOCALE
  i18n.locale = nextLocale
  localStorage.setItem(LOCALE_STORAGE_KEY, nextLocale)
}

export default i18n
