import observer from 'ember-metal/observer';
import on from 'ember-evented/on';
import computed from 'ember-computed';
import Component from 'ember-component';
import { libs } from 'web-client/utilities/friends-list/settings';
import injectService from 'ember-service/inject';

import { InvalidError } from 'ember-ajax/errors';

const MAX_LENGTH = 5;

export default Component.extend({
  store: injectService(),
  session: injectService(),
  recommended: injectService('twitch-friends-list/recommended'),
  tracking: injectService(),

  initRecommended: on('init', function () {
    this.get('recommended').fetchRecommendations();
  }),
  limitedRecommendedList: computed("recommended.recommendedUsers.[]", function () {
    return this.get('recommended.recommendedUsers').slice(0, MAX_LENGTH);
  }),

  _limitedRecommendedListTracking: observer('recommended.recommendedUsers.[]', function () {
    let tracking = this.get('tracking');
    let limitedRecommendedUsers = this.get('recommended.recommendedUsers').slice(0, MAX_LENGTH);

    let trackingObject = {
      login: this.get('session.userData.login'),
      rec_source: this.get('recommended.recommendedSource')
    };

    limitedRecommendedUsers.forEach((user, index) => {
      let i = index + 1;
      trackingObject[`recommended_login_${i}`] = user.get('login');
    });

    tracking.trackEvent({
      services: ['spade'],
      event: 'recommended_friend_display',
      data: trackingObject
    });
  }),

  acceptFriendText: computed("user.displayName", function() {
    let translation = libs.i18n("Accepted {{displayName}}'s request!");
    return translation.replace('{{displayName}}', this.get('user.displayName'));
  }),

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

  actions: {
    addFriend(user) {
      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('didError', true);
        }
      });
    },
    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);
    }
  }
});
