import { nextTick } from 'vue'
import { createI18n } from 'vue-i18n'

export const SUPPORT_LOCALES = ['en', 'de']

var default_options = {
	warnHtmlInMessage: 'off',
	warnHtmlMessage: false,
	fallbackWarn: false,
	silentTranslationWarn: true,
	locale: 'en',
	fallbackLocale: {
		'de':   ['en'],
		'default': ['en']
	}
}

export function setupI18n(options = default_options) {
	const i18n = createI18n(options)
	loadLocaleMessages(i18n, options.locale)
	setI18nLanguage(i18n, options.locale)
	return i18n
}

export function setI18nLanguage(i18n, locale) {
	i18n.locale = 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(i18n, locale) {
	// load locale messages with dynamic import
	const messages = await import(
		/* webpackChunkName: "locale-[request]" */ `./locales/${locale}.json`
	)
  
	// set locale and locale message
	if ('global' in i18n) {
		i18n.global.setLocaleMessage(locale, messages.default)
	} else {
		i18n.setLocaleMessage(locale, messages.default)
	}
  
	return nextTick()
}

export async function loadAndSetLocale (i18n, new_locale) {
	// use locale if paramsLocale is not in SUPPORT_LOCALES
	if (!SUPPORT_LOCALES.includes(new_locale)) {
		//return next(`/${locale}`)
		return
	}

	await loadLocaleMessages(i18n, new_locale)

	// set i18n language
	setI18nLanguage(i18n, new_locale)

	return
}
