import Component from 'ember-component';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';
import injectService from 'ember-service/inject';
import observer from 'ember-metal/observer';
import run from 'ember-runloop';

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

  classNameBindings: [':ember-chat', 'isShowingList:listMode:roomMode'],

  /* args */

  isShowingCreateRoom: null,
  isShowingInviteUser: null,
  room: null,
  isShowingList: null,

  /* methods */

  init() {
    this._super(...arguments);
    this._focusRequested = false;
  },
  _onChatConnected: observer('room', 'room.isLoading', function () {
    if (!this.get('room.isLoading')) {
      run.schedule('afterRender', () => {
        this.reportInteractive();
      });
    }
  }),

  _focusTextareaOnRoomFocus: observer(
    'room', 'isShowingList', 'room.isLoading',
    'isShowingCreateRoom', 'isShowingInviteUser',
  function() {
    let { isAuthenticated } = this.get('session');
    // http://stackoverflow.com/a/326076
    let isEmbed = (function () { try { return window.self !== window.top; } catch (e) { return true; } })();

    if (isAuthenticated && !isEmbed) {
      this._focusRequested = true;
      run.schedule('afterRender', () => {
        if (!this._focusRequested || this.isDestroying || this.isDestroyed) {
          return; // Only run this once per runloop
        }
        this._focusRequested = false;
        if (this.get('isShowingCreateRoom')) {
          this.$('.chat-create-room input:text').focus();
        } else if (this.get('isShowingInviteUser')) {
          this.$('.chat-invite-user input:text').focus();
        } else {
          let room = this.get('room');
          if (room && !this.get('isShowingList') && !room.get('isLoading')) {
            this.$('.chat-interface textarea').focus();
          }
        }
      });
    }
  })

});
