import Helper from 'ember-helper';
import injectService from 'ember-service/inject';

export function containsValue(groupValue, target) {
  if (groupValue) {
    return groupValue.split(',').includes(target);
  }

  return false;
}

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

  init() {
    this._super(...arguments);
    this.result = {};
  },

  compute([experimentKey, targetGroup = 'yes']) {
    let experiments = this.get('experiments');
    let cachedValue = experiments.peekValue(experimentKey);

    if (cachedValue) {
      return containsValue(cachedValue, targetGroup);
    }

    experiments.getExperimentValue(experimentKey).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 false;
  }
});
