import injectService from 'ember-service/inject';
import computed from 'ember-computed';
import Component from 'ember-component';
import { getNonStrangerReason } from 'web-client/utilities/friends-list/reasons';
import { InvalidError } from 'ember-ajax/errors';

export default Component.extend({
  classNames: ['js-friend-info'],

  store: injectService(),
  session: injectService(),
  recommended: injectService('twitch-friends-list/recommended'),
  tracking: injectService(),

  user: null,
  requestPending: false,
  isError: false,

  nonStrangerString: computed(function() {
    // getNonStrangerReason returns a translated string already
    return getNonStrangerReason(this.get('nonStrangerReason'));
  }),

  _removeRecommended(user) {
    this.get('recommended').removeRecommendation(user);
  },

  actions: {
    addFriend(user) {
      this.set('requestPending', true);
      this.get('store').createRecord('friends-list-request', {
        friendId: user.get('id'),
        friendLogin: user.get('login'),
        isRecommended: true
      }).save().then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let friendId = user.get('id');
        this.get('tracking').trackEvent({
          event: 'friend_request',
          data: {
            request_id: `${sessionId}-${friendId}`,
            login: this.get('session.userData.login'),
            target_login: user.get('login'),
            ui_context: 'recommended'
          }
        });
        this.get('tracking').trackEvent({
          event: 'recommended_friend_action',
          data: {
            user_id: sessionId,
            login: this.get('session.userData.login'),
            action: 'accepted',
            target_user_id: friendId,
            target_login: user.get('login')
          }
        });

        this.runTask(() => {
          this._removeRecommended(user);
        }, 500);
      }).catch((e) => {
        // 422 in `ember-ajax` becomes an InvalidError
        if (e instanceof InvalidError) {
          user.get('errors').add('isRequested', 'Requested user already');
        } else {
          user.set('isError', true);
        }
      }).finally(() => {
        this.set('requestPending', false);
      });
    },
    removeRecommendation(user) {
      this.get('tracking').trackEvent({
        event: 'recommended_friend_action',
        data: {
          user_id: this.get('session.userData.id'),
          login: this.get('session.userData.login'),
          action: 'dismissed',
          target_user_id: user.get('id'),
          target_login: user.get('login')
        }
      });
      this.get('recommended').unrecommendUser(user);
    }
  }
});
