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

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

  classNames: ['activity-card', 'js-activity-card'],
  classNameBindings: ['isModal:activity-card--no-border', ':mg-b-1'],
  isModal: false,
  activeUserDataLinks: false,
  canAddComments: computed.alias('post.permissions.can_reply'),
  renderComments: computed('post.comments', 'canAddComments', function () {
    let canAddComments = this.get('canAddComments');
    let commentLength = this.get('post.comments.length');
    return commentLength > 0 || canAddComments;
  }),
  forceEnableEmbeds: computed('post.user.login', function () {
    let channelName = this.get('post.user.login');

    this.get('session').withCurrentUser((user) => {
      if (this.isDestroyed) { return; }
      this.set('forceEnableEmbeds', user.login === channelName);
    });
  }),

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

    this.get('impressionTracking').registerComponent(this, 'enteredViewport');
  },

  willDestroyElement() {
    this.get('impressionTracking').deregisterComponent(this);

    this._super(...arguments);
  },

  click(e) {
    let target = $(e.target);
    if (target.is('.js-feedlink')) {
      this._trackPostLinkClick(e);
    }
  },

  _trackPostLinkClick(e) {
    let feeds = this.get('feeds');
    let channelName = this.get('post.user.login');
    let post = this.get('post');

    feeds.trackEvent("feed_link_click", this.get('trackingInfo'), {
      status_update_id: post.get('id'),
      channel: channelName,
      target_link_text: e.target.innerText,
      target_link_url: e.target.href,
      channel_live: this.get('broadcasterIsLive')
    });
  },

  actions: {
    openPost(post) {
      let handler = this.get('onOpenPost');
      if (handler && handler instanceof Function) {
        handler(post);
      }
    },

    setReactionForPost(emote) {
      let feedsService = this.get('feeds');
      let post = this.get('post');
      let channelName = post.get('user.login');
      let reactions = post.get('reactions');
      let reaction = reactions.findBy('emoteId', emote.id);
      let endorseReaction = reactions.findBy('emoteId', 'endorse');
      let sortedReactions = reactions.sortBy('count').reverse().removeObject(endorseReaction);
      let reactionIndex = 0;
      let reactionType = "add";

      if (!this.get('feeds.meAsFeedUser')) {
        let isModal = this.get('isModal');
        if (!isModal && $.login instanceof Function) {
          $.login();
        }
        return;
      }

      // Capture tracking info before the local data is mutated
      if (emote.id !== 'endorse') {
        if (reaction) {
          sortedReactions.forEach((item, index) => {
            if (item.emoteId === emote.id) {
              // add 1 to account for for the default like
              reactionIndex = index + 1;
            }
          });
        } else {
          reactionIndex = null;
        }
      }

      if (reaction && reaction.userIds[0]) {
        reactionType = "remove";
      }

      feedsService.setReactionForMessage(post, emote).then((/*endorsement*/) => {
        let params = {
          status_update_id: post.get('id'),
          channel: channelName,
          channel_live: this.get('broadcasterIsLive'),
          reaction: emote.id,
          action: reactionType,
          reaction_index: reactionIndex
        };
        if (this.get('isModal')) {
          // Set position to null if the post is viewed in a deep link
          params.feed_index = null;
        }
        feedsService.trackEvent("feed_update_reaction", this.get('trackingInfo'), params);
      });
    },

    enteredViewport() {
      let feeds = this.get('feeds');

      feeds.trackEvent("feed_update_display", this.get('trackingInfo'), {
        status_update_id: this.get('post.id'),
        url: window.location.toString()
      });

      this.get('impressionTracking').deregisterComponent(this);
    },

    trackReactionMenuOpen(clickType, action) {
      let feeds = this.get('feeds');

      feeds.trackEvent("feed_update_expand_reaction", this.get('trackingInfo'), {
        status_update_id: this.get('post.id'),
        channel: this.get('post.user.login'),
        channel_live: this.get('broadcasterIsLive'),
        click_type: clickType,
        action
      });
    }
  }
});
