/* globals Twitch */
import Service from 'ember-service';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import RSVP from 'rsvp';

const API_VERSION = 5;

export default Service.extend({
  dismissed: false,
  layout: injectService(),
  wideEnoughForAds: computed.readOnly('layout.wideEnoughForAds'),

  api: injectService(),

  init() {
    this._super(...arguments);
    this.fetchAsyncAds();
  },

  startCommercial(channelId, duration) {
    let jsonData = JSON.stringify({
      length: duration
    });

    let options = {
      version: API_VERSION,
      contentType: 'application/json; charset=UTF-8'
    };
    return this.get('api').authRequest('post', `channels/${ channelId }/commercial`, jsonData, options);
  },

  getAdBreakSettings(channelId) {
    return this.get('api').authRequest('get', `/kraken/channels/${ channelId }/ads/settings`, {}, { version: API_VERSION });
  },

  fetchAsyncAds() {
    if (!this._asyncAdsPromise) {
      this._asyncAdsPromise = new RSVP.Promise(resolve => {
        Twitch.asyncAds.ready(ads => {
          run(() => {
            // TODO This is really scary!
            // I would love to have a better way or knowing
            // what possible values can be set here.
            this.setProperties(ads);
            resolve();
          });
        });
      });
    }

    return this._asyncAdsPromise;
  },

  visible: computed('enabled', 'wideEnoughForAds', 'dismissed', function () {
    let enabled = this.get('enabled');
    let wideEnough = this.get('wideEnoughForAds');
    let dismissed = this.get('dismissed');

    return enabled && wideEnough && !dismissed;
  }),

  visibleStyle: computed('visible', function () {
    if (this.get('visible')) {
      return '';
    }
    return '<style>.ad_contain, .advertisement{position:absolute !important;margin-left:-100000px !important;visibility:hidden;}</style>';
  }),

  dismiss() {
    this.set('dismissed', true);
  }
});
