/*jshint browser:true */
/*global console, google */

//= require ./index.js

// inspired by https://developers.google.com/interactive-media-ads/docs/use-cases/using_custom_ad_playback
// TODO: expose a contentEnded method that calls this.adsLoader.contentComplete() once, and call for postrolls

(function (Twitch, $) {

  var AdsController = function (options) {
    this.googlePromise = $.getScript('//s0.2mdn.net/instream/html5/ima3.js');
    this.options = options;

    this.$clickTracker = $('.js-clicktracker');
    this.$player = $(options.player);
  };

  // keep controls hidden while clicktracker is shown to allow iOS to capture clicks
  AdsController.prototype.showClickTracker = function () {
    this.$clickTracker.show();
    this.$player.attr('controls', false);
  };

  AdsController.prototype.hideClickTracker = function () {
    this.$clickTracker.hide();
    this.$player.attr('controls', true);
  };

  AdsController.prototype.initialize = function () {
    var self = this;
    return new RSVP.Promise(function (resolve, reject) {
      self.googlePromise.then(function () {
        // Modify the adDisplayContainer constructor call to pass in handles to the
        // content video player and the custom click tracking element.
        self.adDisplayContainer =
          new google.ima.AdDisplayContainer(
            self.options.container,
            self.options.player,
            self.$clickTracker[0]);
        self.adsLoader = new google.ima.AdsLoader(self.adDisplayContainer);
        self.adsManager = null;

        self.adsLoader.addEventListener(
          google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
          self.onAdsManagerLoaded,
          false,
          self);
        self.adsLoader.addEventListener(
          google.ima.AdErrorEvent.Type.AD_ERROR,
          self.onAdError,
          false,
          self);

        self.adDisplayContainer.initialize();
        resolve();

      }).fail(function () {
        $(self).trigger('error');
        reject();
      });
    });
  };

  AdsController.prototype.requestAds = function (adTagUrl) {
    var adsRequest = new google.ima.AdsRequest();
    adsRequest.adTagUrl = adTagUrl;
    var width = $(this.options.player).width();
    var height = $(this.options.player).height();
    adsRequest.linearAdSlotWidth = width;
    adsRequest.linearAdSlotHeight = width;
    adsRequest.nonLinearAdSlotWidth = height;
    adsRequest.nonLinearAdSlotHeight = height;
    this.adsLoader.requestAds(adsRequest);
  };

  AdsController.prototype.onAdsManagerLoaded = function (adsManagerLoadedEvent) {
    console.debug('Ads Manager loaded.');
    this.adsManager = adsManagerLoadedEvent.getAdsManager(this.options.player);
    this.processAdsManager(this.adsManager);
  };

  AdsController.prototype.processAdsManager = function (adsManager) {

    adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
      this.onContentPauseRequested,
      false,
      this);
    adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      this.onContentResumeRequested,
      false,
      this);

    adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      this.onAdError,
      false,
      this);

    var events = [google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
                  google.ima.AdEvent.Type.CLICK,
                  google.ima.AdEvent.Type.COMPLETE,
                  google.ima.AdEvent.Type.FIRST_QUARTILE,
                  google.ima.AdEvent.Type.LOADED,
                  google.ima.AdEvent.Type.MIDPOINT,
                  google.ima.AdEvent.Type.PAUSED,
                  google.ima.AdEvent.Type.RESUMED,
                  google.ima.AdEvent.Type.STARTED,
                  google.ima.AdEvent.Type.THIRD_QUARTILE];
    for (var index = 0; index < events.length; index++) {
      adsManager.addEventListener(
        events[index],
        this.onAdEvent,
        false,
        this);
    }

    adsManager.init(1, 1, google.ima.ViewMode.NORMAL);
    adsManager.start();
    
  };


  AdsController.prototype.onContentPauseRequested = function (adErrorEvent) { };

  AdsController.prototype.onContentResumeRequested = function (adErrorEvent) {
    this.hideClickTracker();
    $(this).trigger('contentResumeRequested');
  };

  AdsController.prototype.onAdEvent = function (adEvent) {
    console.debug('Ad event: ' + adEvent.type);
    switch (adEvent.type) {
    case google.ima.AdEvent.Type.STARTED:
      this.showClickTracker();
      this.options.player.load(); // kludge to get ads to play in desktop safari
      break;
    case google.ima.AdEvent.Type.RESUMED:
      this.showClickTracker();
      break;
    case google.ima.AdEvent.Type.CLICK:
      this.hideClickTracker();
      break;
    case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
      this.hideClickTracker();
      break;
    }
    $(this).trigger(adEvent.type);
  };

  AdsController.prototype.onAdError = function (adErrorEvent) {
    console.error('Ad error: ' + adErrorEvent.getError().toString());
    if (this.adsManager) {
      this.adsManager.destroy();
    }
    this.hideClickTracker();
    $(this).trigger('adError');
  };

  Twitch.player.AdsController = AdsController;

})(Twitch, jQuery);
