import get from 'lodash/get';
import type { Locale, Translations } from '../type';

/* eslint-disable no-prototype-builtins */
export const replace = (template: string | Function, data: Record<string, any>) => {
  if (typeof template === 'function') {
    return template(data);
  }

  return template.replace(/{(\w*)}/g, (m, key) => (data.hasOwnProperty(key) ? data[key] : ''));
};

export const translate = (
  translations: Translations,
  key: string,
  locale: Locale,
  fallbackLocale = 'en',
  data = {}
) => {
  const translation = translations[locale];
  const translationValue = get(translation, key);
  const fallbackValue = get(translations[fallbackLocale], key);

  if (!translation || !translationValue) {
    console.warn(`Warning: no ${key} translation of ${locale}`);
    if (fallbackLocale && fallbackValue) {
      return replace(fallbackValue, data);
    }
    return key;
  }

  if (typeof translations[locale] === 'function' || translations[locale].then) {
    return replace(fallbackValue, data);
  }
  return replace(translationValue, data);
};

export const t = translate;
