import translationKeys from '../translations';

export const i18n = translationKeys;

export const defaultConfig = {
  firstDayOfWeek: 0, // Defaults to 0 (Sunday)
};

let configured = false;

/**
 * Set GitLab UI configuration.
 *
 * @typedef {object} GitLabUIConfiguration
 * @template TValue=string
 * @property {undefined | Object} translations Generic translations for component labels to fall back to.
 * @property {undefined | Number} firstDayOfWeek Configured first day of the week, from 0 (Sunday) to 6 (Saturday).
 * @property {boolean} [accessibleLoadingButton] Temporary flag to enable accessible loading button.
 *
 */
const setConfigs = ({ translations, firstDayOfWeek } = {}) => {
  if (configured) {
    if (process.env.NODE_ENV === 'development') {
      throw new Error('GitLab UI can only be configured once!');
    }

    return;
  }
  configured = true;

  if (typeof firstDayOfWeek === 'number' && firstDayOfWeek >= 0 && firstDayOfWeek <= 6) {
    defaultConfig.firstDayOfWeek = firstDayOfWeek;
  }

  if (typeof translations === 'object') {
    if (process.env.NODE_ENV === 'development') {
      const undefinedTranslationKeys = Object.keys(i18n).reduce((acc, current) => {
        if (!(current in translations)) {
          acc.push(current);
        }
        return acc;
      }, []);
      if (undefinedTranslationKeys.length) {
        /* eslint-disable no-console */
        console.warn(
          '[@gitlab/ui] The following translations have not been given, so will fall back to their default US English strings:',
        );
        console.table(undefinedTranslationKeys);
        /* eslint-enable no-console */
      }
    }

    Object.assign(i18n, translations);
  }
};

export default setConfigs;
