/* globals Twitch */
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import run from 'ember-runloop';
import ClickOutsideMixin from 'web-client/mixins/click-outside';
import { routes } from 'web-client/utilities/friends-list/settings';

export default Component.extend(ClickOutsideMixin, {
  //BZ second binding is a little ugly and probably needs to change.
  classNameBindings: ['isDarkMode:theme--dark'],

  layout: injectService(),
  settings: injectService('chatSettings'),
  session: injectService(),
  search: injectService('twitch-friends-list/search'),
  conversations: injectService('twitch-conversations/conversations'),
  friends: injectService('twitch-friends-list/friends'),
  requests: injectService('twitch-friends-list/requests'),
  whispersShim: injectService('whispers-shim'),
  tracking: injectService(),

  activeTab: 'friends', // Initialize to friends tab
  friendResults: null,
  showFriendsOnboarding: !Twitch.storage.get('sc_friends_onboarding_is_disabled'),
  showWhispersOnboarding: !Twitch.storage.get('sc_whispers_onboarding_is_disabled'),
  friendsRoute: routes.friends,

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

  sortedConversations: computed.readOnly('conversations.sortedConversations'),
  allUserEmotes: computed.alias('conversations.allUserEmotes'),
  displayableFriends: computed.alias('friends.displayableFriends'),
  offlineFriends: computed.alias('friends.offlineFriends'),
  showOfflineFriends: computed('offlineFriends', function() {
    return this.get('offlineFriends.length');
  }),
  hasQuery: computed.notEmpty('query'),

  isDarkMode: computed.or('settings.darkMode', 'layout.isTheatreMode'),
  shouldDisplayCount: computed('requests.notificationsCount', 'requests.isNotificationsCountLoading', function() {
    // We have to make sure it's done loading otherwise it'll display "NULL"
    return !this.get('requests.isNotificationsCountLoading') &&
            this.get('requests.notificationsCount') > 0;
  }),
  showViewAllFriends: computed.readOnly('friends.friends.length', function() {
    return this.get('friends.friends.length') > 0;
  }),

  init() {
    this._super(...arguments);
    if (this.get('session').isAuthenticated) {
      this.get('conversations').setupService();
      this.get('conversations').initialSyncUnreadCounts();
    }
  },

  didInsertElement() {
    this.$('.js-social-column-list').on('scroll mousedown wheel DOMMouseScroll mousewheel', this.get('_scrollHandler').bind(this));
    this.$('.js-social-column-list-container.scroll').TrackpadScrollEmulator({
      wrapContent: false,
      scrollbarHideStrategy: 'rightAndBottom'
    });
  },

  willDestroyElement(){
    this._super(...arguments);
    this.$('.js-social-column-list').off('scroll mousedown wheel DOMMouseScroll mousewheel');
    if (this.$('.js-social-column-list-container.scroll').data('plugin_TrackpadScrollEmulator')) {
      this.$('.js-social-column-list-container.scroll').TrackpadScrollEmulator('destroy');
    }
  },

  _scrollHandler() {
    this.debounceTask('_maybeFetchMoreResults', 100);
  },

  _maybeFetchMoreResults() {
    if (this._isLastItemVisible()) {
      switch (this.get('activeTab')) {
        case 'whispers':
          return this.get('conversations').fetchMoreThreads();
        case 'friends':
          return this.get('friends').showMoreFriends();
      }
    }
  },

  _isLastItemVisible() {
    let $container = this.$('.js-social-column-list')[0];
    let $lastThread = this.$('.js-social-column-list .js-social-column-list-item').last()[0];
    if ($container && $lastThread) {
      let targetRect = $lastThread.getBoundingClientRect();
      let containerRect = $container.getBoundingClientRect();
      return targetRect.top <= containerRect.bottom;
    }
  },

  openConversation(login) {
    this.get('conversations').openConversation(login);
  },

  clickedOutside() {
    this._clearSearch();
  },

  _search(query) {
    if (this.isDestroyed) { return; }
    this.get('search').search(query).then(results => {
      if (this.isDestroyed) { return; }
      if (this.get('query').trim().toLowerCase() !== query) {
        //
        // If the query changed while we were fetching results, throw
        // away the results.
        //
        return;
      }
      this.set('searchResults', results);
    }, (e) => {
      if (this.isDestroyed) { return; }
      this.set('hasSearchError', true);
      throw e;
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.set('isSearchLoading', false);
    });
  },

  _clearSearch() {
    this.set('searchResults', null);
    this.set('friendResults', null);
    this.set('query', '');
    this.set('isSearchLoading', false);
    this.set('hasSearchError', false);
  },

  _scrollToTop() {
    this.$('.js-social-column-list').scrollTop(0);
  },

  actions: {
    search(query) {
      if (this.get('query') === query) {
        return;
      }

      this.set('isSearchLoading', true);
      this.set('query', query);
      query = query.trim().toLowerCase();

      if (!query) {
        this._clearSearch();
        return;
      }

      let friends = this.get('friends').search(query);
      this.set('friendResults', friends);

      run.debounce(this, '_search', query, 500);
    },

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

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

    closeConversation() {
      this.get('conversations').closeConversation();
    },

    setActiveTab(tab) {
      this._clearSearch();
      this._scrollToTop();
      this.set('activeTab', tab);
    },

    disableFriendsOnboarding() {
      Twitch.storage.set('sc_friends_onboarding_is_disabled', true);
      this.set('showFriendsOnboarding', false);
    },

    disableWhispersOnboarding() {
      Twitch.storage.set('sc_whispers_onboarding_is_disabled', true);
      this.set('showWhispersOnboarding', false);
    }
  }
});
