/* globals window */
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import { htmlSafe } from 'ember-string';
import computed from 'ember-computed';

const TWITCH_EXT_LOADED = 'twitch-ext-loaded';
const TWITCH_EXT_BOOTSTRAP = 'twitch-ext-bootstrap';
const EVENT_MESSAGE = 'message';

// Note that to test this in development you must
// change config/environment.js ENV['pubsub'] environment to
// 'production' from 'darklaunch'

export default Component.extend({
  pubsub: injectService(),
  messageReceiveCount: 0,
  extensionInstallation: null,
  extension: computed.alias('extensionInstallation.extension'),

  testAllowSameOrigin: false,

  frameStyle: computed('extension.panelHeight', function() {
    let panelHeight = this.get('extension.panelHeight') || 300;
    return htmlSafe(`height: ${panelHeight}px`);
  }),

  onMessage(event) {
    // CHECK if event is coming from the iframe owned by this component.
    let iframe = this.$('iframe');
    let iframeWindow = iframe.get(0).contentWindow;
    if (iframeWindow === event.originalEvent.source) {
      if(
        typeof event.originalEvent.data === 'object' &&
        'action' in event.originalEvent.data &&
        event.originalEvent.data.action === TWITCH_EXT_LOADED
      ) {
        this.set('messageReceiveCount', this.get('messageReceiveCount')+1);

        let auth = this.get('extensionInstallation.token');
        let clientId = this.get('extension.clientId');

        // This is a load message from the iframe created by this component
        let response = {
          action: TWITCH_EXT_BOOTSTRAP,
          bootstrap: { clientId, auth }
        };

        // The targetOrigin of this postMessage has to be '*' because
        // the origin of a sandboxed iframe without 'allow-same-origin'
        // will have an origin of "null".
        iframeWindow.postMessage(response, '*');
      }
    }
  },

  init() {
    this._super(...arguments);
    this.set('boundOnMessage', this.get('onMessage').bind(this));
    let clientId = this.get('extension.clientId');
    this.set('pubsubControlTopicName', `extension-control.${clientId}`);
  },

  didInsertElement() {
    this._super(...arguments);
    this.$(window).on(EVENT_MESSAGE, this.get('boundOnMessage'));
    let pubsubControlTopicName = this.get('pubsubControlTopicName');
    this.get('pubsub').on(pubsubControlTopicName, this, this.handlePubsub);
  },

  didReceiveAttrs() {
    this._super(...arguments);
    this.attrs.refreshPanelLayout();
  },

  willDestroyElement() {
    this._super(...arguments);
    this.$(window).off(EVENT_MESSAGE, this.get('boundOnMessage'));
    let pubsubControlTopicName = this.get('pubsubControlTopicName');
    this.get('pubsub').off(pubsubControlTopicName, this, this.handlePubsub);
  },

  handlePubsub(payload) {
    let clientId = this.get('extension.clientId');
    if (payload.action === 'kill' && payload.clientId === clientId) {
      this.$('iframe').remove();
    }
  },

  actions: {
    toggleEnableDisable() {
      alert('TODO: This will toggle enable/disable');
    },

    flagProblem() {
      alert('TODO: This will allow user to flag a problem extension');
    }
  }
});
