/* globals Twitch */
import Ember from 'ember';
import computed from 'ember-computed';

const { inject, $, Component } = Ember;

export default Component.extend({
  classNames: ['activity-react', 'clearfix'],
  emotes: inject.service('user-emotes'),
  feeds: inject.service(),

  showEmoticonSelector: false,
  showAllReactions: false,
  isLoggedIn: computed(function () {
    return Twitch.user.isLoggedIn();
  }),

  init() {
    this._super(...arguments);
    let emotes = this.get('emotes');

    emotes.populate().then((rawEmoteSet) => {
      this.set('rawEmoteSet', rawEmoteSet);
    });
  },

  sortedReactions: computed('reactions.[]', function () {
    let reactions = this.get('reactions');
    return reactions.sort(this._sortReactions);
  }),

  endorseReaction: computed('sortedReactions', function () {
    let sortedReactions = this.get('sortedReactions');
    let endorseReaction = sortedReactions.findBy('emoteId', 'endorse');
    return endorseReaction || {emoteId: "endorse", emoteName: "endorse"};
  }),

  topReactions: computed('sortedReactions', 'endorseReaction', function () {
    let topReactions = [];
    let sortedReactions = this.get('sortedReactions');
    let endorseReaction = this.get('endorseReaction');

    for (let i = 0; i < sortedReactions.length; i++) {
      let reaction = sortedReactions[i];
      if (topReactions.length === 3) {
        break;
      }
      if (reaction !== endorseReaction) {
        topReactions.push(reaction);
      }
    }
    return topReactions;
  }),

  additionalReactions: computed('sortedReactions', 'endorseReaction', 'topReactions', function () {
    let additionalReactions = [];
    let sortedReactions = this.get('sortedReactions');
    let endorseReaction = this.get('endorseReaction');
    let topReactions = this.get('topReactions');

    for (let i = 0; i < sortedReactions.length; i++) {
      let reaction = sortedReactions[i];
      if (reaction !== endorseReaction && !topReactions.includes(reaction)) {
        additionalReactions.push(reaction);
      }
    }

    return additionalReactions;
  }),

  didInsertElement() {
    this._super(...arguments);

    this.addEventListener(document.body, 'click', (e) => {
      if ($(e.target).closest(`#${this.elementId} .js-reactions-menu`).length === 0) {
        this.set('showEmoticonSelector', false);
        this.set('showAllReactions', false);
      }
    });
  },

  _sortReactions(reactionA, reactionB) {
    let reactionAEndorsed = reactionA.userIds.length > 0;
    let reactionBEndorsed = reactionB.userIds.length > 0;
    let equalCounts = reactionA.count === reactionB.count;
    let sortResponse;
    if (equalCounts && reactionAEndorsed && !reactionBEndorsed) {
      sortResponse = -1;
    } else if (equalCounts && reactionBEndorsed && !reactionAEndorsed) {
      sortResponse = 1;
    } else {
      sortResponse = reactionB.count - reactionA.count;
    }
    return sortResponse;
  },

  actions: {
    toggleReactionsMenu(menu) {
      let trackingHandler = this.get('onExpand');
      let menuOpen;

      if (menu === "selector") {
        menuOpen = this.get('showEmoticonSelector');
        this.set('showAllReactions', false);
        this.toggleProperty('showEmoticonSelector');
      } else {
        menuOpen = this.get('showAllReactions');
        this.set('showEmoticonSelector', false);
        this.toggleProperty('showAllReactions');
      }

      if (trackingHandler instanceof Function) {
        trackingHandler(menu, menuOpen ? "close" : "open");
      }
    },

    setReactionByName(emoteName) {
      let emotes = this.get('emotes');
      emotes.parseEmotes(emoteName).then((emoteObj) => {
        let emote = {
          id: emoteObj[0].id,
          name: emoteName
        };
        this.send('setReactionForPost', emote);
      });
    },

    hideEmoticonSelector() {
      this.set('showEmoticonSelector', false);
    },

    setReactionForPost(emote) {
      let reactionHandler = this.get('onReaction');

      if (emote.id === 1) {
        emote.id = 'endorse';
        emote.name = 'endorse';
      }

      if (reactionHandler instanceof Function) {
        reactionHandler(emote);
        this.set('showEmoticonSelector', false);
        $('.tipsy.tipsy-n').remove();
      }
    }
  }
});
