/* globals i18n */

import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import { assign } from 'ember-platform';
import env from 'web-client/config/environment';
import SearchRequest from 'web-client/utilities/navigation-search/search-request';
import { buildCommunityCategory } from 'web-client/components/navigation-search/utils/category';
import { commatized } from 'web-client/helpers/commatized';

const STREAM_TRANSLATED = i18n('{{num}} stream');
const STREAMS_TRANSLATED = i18n('{{num}} streams');

export default Component.extend({
  search: injectService(),

  /* stubbed communities */
  communities: injectService(),

  /* passed in properties */
  channel: null,
  community: null,
  communityName: '',
  communityChange: null,

  /* internal properites */
  placeholder: i18n('Search for a community'),
  hasFocus: false,

  request: this.request || SearchRequest.create(),
  term: '',
  category: buildCommunityCategory(),
  categoryId: 'communities',
  searchResults: [],
  showResults: computed('searchResults', 'hasFocus', function() {
    return this.get('hasFocus') && this.get('searchResults').length > 0;
  }),

  hoveredResult: null,
  hoveredDescription: computed('hoveredResult', function() {
    return this.get('hoveredResult.summary') || this.get('hoveredResult.short_description');
  }),
  hoveredRules: computed('hoveredResult', function() {
    return this.get('hoveredResult.rules_html') || this.get('hoveredResult.rules');
  }),
  hoveredChannels: computed('hoveredResult', function() {
    return this.get('hoveredResult.channels');
  }),
  translatedStreams: computed('hoveredChannels', function() {
    let num = this.get('hoveredChannels');
    if (!num) {
      return STREAMS_TRANSLATED.replace('{{num}}', 0); // no streams
    } else if (num === 1) {
      return STREAM_TRANSLATED.replace('{{num}}', num);
    }
    return STREAMS_TRANSLATED.replace('{{num}}', commatized(num));
  }),
  selectedIndex: 0,

  init() {
    this._super(...arguments);
    this.get('communities').getChannelCommunity(this.get('channel._id')).then(result => {
      if (this.isDestroyed) { return; }

      if(result && result.name) {
        this.set('community', result);
        this.set('communityName', result.name);
      }
    });
  },

  actions : {
    // necessary because <input> is one way binding
    inputChange(value) {
      this.set('term', value);
      this.set('communityName', value);
      return value.length < 1 ? this.set('searchResults', []) : this.query();
    },

    focusIn() {
      this.set('hasFocus', true);
    },

    focusOut() {
      this.set('hasFocus', false);
      this.get('communityChange')();
    },

    hoverResult(result, index) {
      let previousIndex = this.get('selectedIndex');
      this.$(`li.balloon__link:eq(${previousIndex})`).removeClass('balloon__link--active');
      this.set('hoveredResult', result);
      this.set('selectedIndex', index);
      this.set('term', result.name);
      this.set('communityName', result.name);
      this.$(`li.balloon__link:eq(${index})`).addClass('balloon__link--active');
    },

    selectResult(result) {
      this.set('term', result.name);
      this.set('communityName', result.name);
      this.send('focusOut');
    }
  },

  query(options = {}) {
    let currentCategoryId = this.get('categoryId');
    let page = options.page || 0;
    let term = this.get('term');
    let debounce = env.delay.search.updateTerm;

    this.get('request').start(assign(options, {
      debounce,

      request: () => {
        let queryOptions = { page };
        return this.get('search').queryForType(currentCategoryId, term, queryOptions);
      },

      success: (results) => {
        let totalHitCount = 0;
        let category = this.get('category');
        category.set('search', results[category.get('id')]);
        totalHitCount += category.get('totalHitCount');

        this.set('searchResults', category.get('hits'));
      }
    }));
  }
});
