import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
import lang from './languages';

i18n.fallbacks = true;

i18n.translations = {
  en: lang.en,
  es: lang.es
};

RNLocalize.getLocales().forEach(({ languageCode }) => {
  if (lang[languageCode]) i18n.translations[languageCode] = lang[languageCode];
});

const missingTranslationRegex = /^\[missing ".*" translation\]$/;

// This function is a wrapper to avoid exception wich leads in a crash
const translateOrFallback = (initialMsg: any, options?: any) => {
  // We tried to translate something else than a string
  // The native i18n function will simply crash instead of rejecting the attempt with an error message
  if (typeof initialMsg !== 'string') {
    if (__DEV__) {
      // eslint-disable-next-line no-restricted-syntax
      // console.log(
      //   `i18n: you must give a string to translate instead of "${typeof initialMsg}"`
      // );
    }
    return ''; // We don't return any message as we don't know what to send
  }

  const localMsg = i18n.t(initialMsg, options);

  if (missingTranslationRegex.test(localMsg)) {
    if (__DEV__) {
      // eslint-disable-next-line no-restricted-syntax
      // console.log(
      //   `translation "${initialMsg}" does not exists in translations files`
      // );
    }
    return initialMsg;
  }

  return localMsg;
};

export default {
  ...i18n,
  t: translateOrFallback
};
