import Helper from 'ember-helper';
import injectService from 'ember-service/inject';
import { EXPERIMENT_NAME } from 'web-client/services/intl-i18n';

export default Helper.extend({
  experiments: injectService(),
  intlI18n: injectService(),
  intl: injectService(),

  compute([key, defaultString]) {
    let experiments = this.get('experiments');
    let intl = this.get('intl');
    let intlI18n = this.get('intlI18n');
    let cachedValue = experiments.peekValue(EXPERIMENT_NAME);

    if (cachedValue) {
      if (cachedValue === 'enabled') {
        return intl.t(key);
      }

      return defaultString;
    }

    intlI18n.getExperimentPromise().then((value) => {
      if (this.isDestroyed) { return; }
      // Don't recompute if value is falsey. There is no point in recomputing
      // because the return value will still be falsey and it will cause an
      // infinite loop.
      if (value) {
        this.recompute();
      }
    });

    return defaultString;
  }
});
