/* globals Twitch */
import Service from 'ember-service';
import injectService from 'ember-service/inject';

const REC_HOLDOUT_PERCENT = 0.01;
const REC_HOLDOUT_SEED    = 'aardvark';
const REC_MAX_HEX         = 'ffffffffffffffffffffffffffffffffffffffff';

export default Service.extend({

  session:  injectService(),
  crypto:   injectService(),
  tracking: injectService(),

  shouldShowRecs: false,

  trackRecsHoldout() {

    let recsHoldout = false;
    let userId = this.get('session.userData.id');
    let isStaff = this.get('session.userData.is_staff');

    if (userId !== null && userId !== undefined && !isStaff) {
      let hashedId = this._calculateRecHoldoutSplit(userId);
      recsHoldout = hashedId < REC_HOLDOUT_PERCENT;

      this.get('tracking').trackEvent({
        event: 'anteater',
        data: {
            time:       Date.now(),
            login:      this.get('session.userData.login'),
            user_id:    this.get('session.userData.id'),
            device_id:  Twitch.idsForMixpanel.getOrCreateUniqueId(),
            is_enabled: recsHoldout,
            is_staff:   isStaff
          }
      });
    }
    this.set('shouldShowRecs', !recsHoldout);
  },

  _calculateRecHoldoutSplit(userId) {
    let seededId = REC_HOLDOUT_SEED + userId;
    let hashedSeed = this.get('crypto').SHA1(seededId);

    return parseInt(hashedSeed, 16) / parseInt(REC_MAX_HEX, 16);
  }
});
