import Component from 'ember-component';
import injectService from 'ember-service/inject';
import $ from 'jquery';
import on from 'ember-evented/on';

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

  sendData: on('didInsertElement', function() {
    this._super(...arguments);

    let { isAuthenticated, userData } = this.get('session');
    if (!isAuthenticated || !userData) {
      return;
    }

    let options = {
      headers: {
        Authorization: `OAuth ${userData.chat_oauth_token}`
      }
    };
    
    let api = this.get('api');

    api.request('get', '/api/streamplus/user', {}, options).then(data => {
      if ($('#sp-content-iframe').length !== 1) {
        return;
      }
      $('#sp-content-iframe').on('load', function() {
        $('#sp-content-iframe')[0].contentWindow.postMessage(
          data,
          'https://d2efawz2w4dk8h.cloudfront.net'
        );
      });
    });
  })
});
