import Service from 'ember-service';
import injectService from 'ember-service/inject';
import config from 'web-client/config/environment';
import RSVP from 'rsvp';

const BITS_FOR_ADS_EXPERIMENT_NAME = 'BITS_FOR_ADS';

export default Service.extend({
  globals: injectService(),
  geo: injectService(),
  session: injectService(),
  experiments: injectService(),

  isEnabled(channelName) {
    if (!this.get('globals.AdsForBits')) {
      return RSVP.resolve(false);
    }

    // true[X] doesn't support Safari (disable check in tests)
    if (config.environment !== 'test') {
      let ua = navigator.userAgent;
      if (ua.indexOf('Safari') !== -1 && ua.indexOf('Chrome') === -1) {
        return RSVP.resolve(false);
      }
    }

    let session = this.get('session');
    let isStaff = session.userData && session.userData.is_staff;
    let inQaBitsPartnerChannel = channelName === 'qa_bits_partner';
    let inNerolabsChannel = channelName === 'nerolabs';

    let isInChannelOverride = (isStaff && inQaBitsPartnerChannel) || inNerolabsChannel;

    let geoPromise = this.get('geo').getGeo();
    let experimentPromise = this.get('experiments').getExperimentValue(BITS_FOR_ADS_EXPERIMENT_NAME);

    return RSVP.all([geoPromise, experimentPromise]).then(([geoData, experimentValue]) => {
      if (geoData.geo === 'US') {
        if (isInChannelOverride) {
          return true;
        } else if (experimentValue === 'on') {
          return true;
        }
      }

      return false;
    }).catch(() => {
      return false;
    });
  }
});
