import _ from 'lodash';
import { config } from '~/config';

// RTL languages not supported
// import { I18nManager } from 'react-native';
import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
import { TextService } from 'nixplay-ui-kit';
import { translations } from './translations';

i18n.translations = translations;
i18n.fallbacks = config.env === 'prod' ? 'en' : false;
// const fallback = { languageTag: 'en', isRTL: false };
const fallback = { languageTag: 'en' };
// const { languageTag, isRTL } = RNLocalize.findBestAvailableLanguage(Object.keys(i18n.translations)) || fallback;
const { languageTag } = RNLocalize.findBestAvailableLanguage(Object.keys(i18n.translations)) || fallback;
// I18nManager.forceRTL(isRTL); // optional, you might not want to handle RTL
i18n.locale = languageTag || 'en';
// track the previous locale
i18n.prevLocale = null;

// Store OS Language
i18n.OSLanguage = _.get(RNLocalize.getLocales(), '[0].languageCode', languageTag);

i18n.tWithComponent = (key, params, elements = [], textWrapper) => {
	const defaultText = `translation not supported: ${i18n.currentLocale()}`;
	const modifiedParams = Object.assign(params || {}, { defaultValue: defaultText });
	const wrapper = _.isFunction(textWrapper) ? textWrapper : (text) => (text);
	let remaining = i18n.t(key, modifiedParams);
	if (defaultText === remaining) return remaining;

	const result = [];
	elements.forEach((func, idx) => {
		const [prefix, others] = remaining.split(`<${idx}>`);
		if (others) {
			const [toWrap, suffix = ''] = others.split(`</${idx}>`);
			result.push(wrapper(prefix), func(toWrap));
			remaining = suffix;
		}
	});
	result.push(wrapper(remaining));
	return result;
};

export const updateComponentText = () => {
	if (TextService && _.isFunction(TextService.setLocale)) {
		TextService.setLocale(i18n.locale);
	}
	if (TextService && _.isFunction(TextService.setText)) {
		TextService.setText({
			loading: i18n.t('common.loading'),
			playlistFull: i18n.t('playlists.playlistFull'),
		});
	}
};
updateComponentText();

export default i18n;
