import Component from 'ember-component';
import { assert } from 'ember-metal/utils';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';

export default Component.extend({
  googletag: injectService(),
  session: injectService(),

  slotName: null,
  slotClass: null,
  slotDimensions: null,
  slotId: null,

  // Overrideable in some cases (e.g. sizzle strip)
  slotAdUnit: 'homepage',

  isVisible: computed.not('googletag.isBlocked'),

  didReceiveAttrs() {
    this._super(...arguments);

    let componentName = this.toString();
    assert(`${componentName} requires a slotId argument`, !!this.get('slotId'));
    assert(`${componentName} requires a slotName argument`, !!this.get('slotName'));
    assert(`${componentName} requires a slotDimensions argument`, !!this.get('slotDimensions'));
  },

  didInsertElement() {
    this._super(...arguments);

    let googletag = this.get('googletag');
    let adUnit = this.get('slotAdUnit');
    let { isAuthenticated } = this.get('session');
    let targetingParams = {
      server: 'production',
      pagetype: 'homepage',
      salt: window.location.protocol === 'https:' ? 'true' : 'false',
      loggedin: isAuthenticated ? 'true' : 'false'
    };

    this._slot = googletag.createSlot({
      adUnitPath: googletag.dfpAdUnitPathFor(adUnit),
      size: this.get('slotDimensions'),
      div: this.get('slotId'),
      targetingParams
    });
  },

  willDestroyElement() {
    this.get('googletag').destroySlot(this._slot);
    this._super(...arguments);
  }
});
