/* eslint-disable no-prototype-builtins */
import template from 'lodash/template';
import en from './en';
import zh from './zh';

// eslint-disable-next-line import/prefer-default-export
export const translations = {
  zh,
  en,
};

const replace = (t: string, data: Record<string, any> = {}): string => {
  try {
    const compiled = template(t, { interpolate: /{([\s\S]+?)}/g, escape: /{([\s\S]+?)}/g });
    return compiled(data);
  } catch (e) {
    console.error(`Error evaluating template: ${t}`, e);
    return '';
  }
};
export const createTranslator = ({ fallbackLocale = 'en' }: { fallbackLocale?: string }, langs: any = translations) => {
  return (key: string, locale = fallbackLocale, data: Record<string, any> = {}) => {
    if (!langs[locale] || !langs[locale][key]) {
      if (fallbackLocale && langs[fallbackLocale]?.[key]) {
        return replace(langs[fallbackLocale]?.[key], data);
      }

      return key;
    }

    // @ts-ignore
    return replace(langs[locale][key], data);
  };
};

export const translate = createTranslator({ fallbackLocale: 'en' });
export const t = translate;
