/* globals Twitch, i18n */
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
import config from 'web-client/config/environment';

export default Component.extend({
  tagName: 'span',
  feeds: injectService(),
  notify: injectService(),

  twitterConnectPromise: null,
  twitterInterval: null,

  startTwitterConnect() {
    if (this.twitterConnectPromise) {
      return this.twitterConnectPromise;
    }

    return this.twitterConnectPromise = new RSVP.Promise((resolve, reject) => {
      let clientId = Twitch.api.config.clientID;
      let userID = this.get('feeds.meAsFeedUser.id');
      let path = `${Twitch.api.config.baseUrl}/v4/twitter/${userID}/auth?client_id=${clientId}`;
      let twitterPopout = window.open(path, 'twitterPopout', 'width=800,height=540');
      let twitterInterval = setInterval(() => {
        if (twitterPopout) {
          if (this.isDestroyed || this.isDestroying) { return; }
          if (twitterPopout.success) {
            resolve();
            clearInterval(twitterInterval);
            twitterPopout.close();
            return;
          }
          if (twitterPopout.error) {
            reject();
            clearInterval(twitterInterval);
            twitterPopout.close();
            this.twitterConnectPromise = null;
            return;
          }
          if (twitterPopout.closed) {
            reject();
            clearInterval(twitterInterval);
            this.twitterConnectPromise = null;
            return;
          }
        }
      }, config.delay.channelFeed.twitterPopout);
      this.set('twitterAuthInterval', twitterInterval);
    });
  },

  willDestroy() {
    this._super(...arguments);
    let twitterInterval = this.get('twitterAuthInterval');
    if (twitterInterval) {
      clearInterval(twitterInterval);
    }
  },

  actions: {
    twitterConnect() {
      let notify = this.get('notify');
      let feeds = this.get('feeds');
      this.startTwitterConnect().then(() => {
        if (this.isDestroyed) { return; }
        notify.success(i18n('Twitter connect succeeded'));
        feeds.set('meAsFeedUser.twitterConnected', true);
      }, () => {
        if (this.isDestroyed) { return; }
        notify.error(i18n('Connection canceled'));
      });
    }
  }
});
