/* global uuid */
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import $ from 'jquery';

export default Component.extend({
  session: injectService(),
  truexAds: injectService(),
  crypto: injectService(),
  globals: injectService(),
  classNames: ['bits-ad-provider--truex'],

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

  _requestAd() {
    this.set('requestId', uuid());
    let truexAds = this.get('truexAds');
    if (!truexAds.isInitialized()) {
      this._postMessage('adblock');
      return;
    }

    let tuid = this.get('crypto').SHA1(`${this.get('session.userData.id')}`);
    let configHash = this.get('globals.truexPartnerHash');

    truexAds.client({
      'network_user_id': tuid,
      'partner_config_hash': configHash
    }, (client) => {
      client.requestActivity((activity) => {
        this._postMessage('requestAd', {
          'activity': JSON.stringify(activity)
        });

        if (activity) {
          this._loadAd(client, activity);
        } else {
          this._postMessage('limitReached');
        }
      });
    });
  },

  _loadAd(client, activity) {
    this._postAdDimensions(activity);
    this._attachCallbacks(activity);

    client.loadActivityIntoContainer(activity, this.$().get(0));
  },

  _postAdDimensions(activity) {
    // prevent scrollbars from the truex iframe
    $('html, body').css('overflow', 'hidden');

    this._postMessage('dimensions', {
      'width': activity.window_width,
      'height': activity.window_height
    });
  },

  _attachCallbacks(activity) {
    activity.onStart((currentActivity) => {
      this._postMessage('onStart', {
        'activity': JSON.stringify(currentActivity)
      });
    });
    activity.onFinish((currentActivity) => {
      this._postMessage('onFinish', {
        'activity': JSON.stringify(currentActivity)
      });
    });
    activity.onCredit((engagement) => {
      this._postMessage('onCredit', {
        'engagement': JSON.stringify(engagement)
      });
    });
    activity.onClose((currentActivity) => {
      this._postMessage('onClose', {
        'activity': JSON.stringify(currentActivity)
      });
    });
  },

  _postMessage(type, data) {
    window.parent.postMessage($.extend({
      'msgSrc': 'trueXAd',
      'msgType': type,
      'requestId': this.get('requestId')
    }, data), '*');
  }
});
