import injectService from 'ember-service/inject';
import Component from 'ember-component';
import computed from 'ember-computed';
import $ from 'jquery';
import run from 'ember-runloop';

const CONV_WINDOW_WIDTH = 310,
      CONV_WINDOW_COLLAPSED_WIDTH = 223;

export default Component.extend({
  classNames: ['conversations-manager'],

  store: injectService(),
  conversations: injectService('twitch-conversations/conversations'),
  session: injectService(),

  allConversations: computed.readOnly('conversations.allConversations'),
  sortedConversations: computed.readOnly('conversations.sortedConversations'),

  init() {
    this._super(...arguments);
    if (this.get('session').isAuthenticated) {
      this.get('conversations').setupService();
      this.get('conversations').on('displayConversation', this, this._displayConversation);
      this.get('conversations').on('maximizeConversation', this, this._maximizeConversation);
      this.get('conversations').initialSyncUnreadCounts();
    }
  },

  allUserEmotes: computed.alias('conversations.allUserEmotes'),

  didInsertElement() {
    this._super();
    $('.app-main').addClass('has-conversations');
    this.addEventListener(window, 'resize', () => {
      this._onWindowResize();
    });
  },

  _onWindowResize() {
    let widthUsed = 0,
        widthAvailable = this.$().outerWidth();

    widthUsed += this.$('.conversations-list-icon').outerWidth();
    this.$('.conversation-window').each((i, conversationWindow) => {
      widthUsed += $(conversationWindow).outerWidth(true);
    });

    if (widthUsed > widthAvailable) {
      this._hideLastActive();
    } else if (widthAvailable - widthUsed > CONV_WINDOW_WIDTH) {
      this._displayNextActive();
    }
  },

  _hideLastActive() {
    let displayed = this.get('sortedConversations').filterBy('isDisplayed'),
        convToHide = displayed.popObject();
    if (convToHide) {
      if (convToHide.get('isFocused') && displayed.length > 1) {
        convToHide = displayed.popObject();
      }
      convToHide.set('isDisplayed', false);
    }
  },

  _displayNextActive() {
    let availableActives = this.get('sortedConversations').filterBy('isActive').rejectBy('isDisplayed');
    if (availableActives.length > 0) {
      this._displayConversation(availableActives.objectAt(0));
    }
  },

  _displayConversation(conversation) {
    let widthUsed = 0,
        widthAvailable = $('.conversations-content').outerWidth();

    widthUsed += this.$('.conversations-list-icon').outerWidth();
    this.$('.js-conversation-window').each((i, conversationWindow) => {
      widthUsed += $(conversationWindow).outerWidth(true);
    });

    if (!conversation.get('isDisplayed')) {
      if ((widthAvailable - widthUsed) < CONV_WINDOW_WIDTH) {
        this._hideLastActive();
        // This is to fix an issue in Safari and Firefox where the new window is added first,
        // causing an inaccessible white box to block the screen as the windows overflow
        run.schedule('afterRender', this, function () {
          conversation.set('isDisplayed', true);
        });
      } else {
        conversation.set('isDisplayed', true);
      }
    }
  },

  _maximizeConversation(conversation) {
    let widthUsed = 0,
        widthAvailable = $('.conversations-content').outerWidth();

    widthUsed += this.$('.conversations-list-icon').outerWidth();
    this.$('.js-conversation-window').each((i, conversationWindow) => {
      widthUsed += $(conversationWindow).outerWidth(true);
    });

    if (conversation.get('isCollapsed')) {
      let spaceNeeded = CONV_WINDOW_WIDTH - CONV_WINDOW_COLLAPSED_WIDTH;
      if ((widthAvailable - widthUsed) < spaceNeeded) {
        this._hideLastActive();
        run.schedule('afterRender', this, function () {
          conversation.set('isCollapsed', false);
        });
      } else {
        conversation.set('isCollapsed', false);
      }
    }
  },

  actions: {
    openInModal(template, context) {
      this.sendAction('openInModal', template, context);
    },

    closeModal() {
      this.sendAction('closeModal');
    }
  }
});
