import Component from 'ember-component';
import computed from 'ember-computed';
import { storageFor } from 'ember-local-storage';
import injectService from 'ember-service/inject';
import { getNonStrangerReason } from 'web-client/utilities/friends-list/reasons';

export default Component.extend({
  store: injectService(),
  session: injectService(),
  tracking: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  request: null,
  blocked: null,
  settings: storageFor('twitch-friend-settings'),
  askBlock: computed('request.isRejected', 'blocked', function () {
    // Uncomment when we want to enable blocking.
    // return this.get('request.isRejected') && isEqual(this.get('blocked'), null);
    return false;
  }),

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

  _manageRequest(request, action) {
    return this.get('requests')[action](request);
  },

  actions: {
    accept() {
      this.set('settings.onboardingDismissed', true);
      this._manageRequest(this.get('request'), 'accept').then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let friendId = this.get('request.user.id');
        this.get('tracking').trackEvent({
          event: 'friend_request_response',
          data: {
            request_id: `${friendId}-${sessionId}`,
            action: 'accept',
            login: this.get('session.userData.login'),
            requester_login: this.get('request.user.login'),
            ui_context: 'friend_requests',
            was_recommendation: this.get('request.isRecommended')
          }
        });
        this.attrs.onResolve();
      });
    },
    reject() {
      this._manageRequest(this.get('request'), 'reject').then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let friendId = this.get('request.user.id');
        this.get('tracking').trackEvent({
          event: 'friend_request_response',
          data: {
            request_id: `${friendId}-${sessionId}`,
            action: 'decline',
            login: this.get('session.userData.login'),
            requester_login: this.get('request.user.login'),
            ui_context: 'friend_requests',
            was_recommendation: this.get('request.isRecommended')
          }
        });
        this.attrs.onResolve();
      });
    },
    block() {
      const request = this.get('request');
      this.get('store').queryRecord('friends-list-user', {
        type: 'block',
        id: request.get('user.id')
      }).then(() => {
        this.set('blocked', true);
        this.attrs.onResolve(request);
      });
    },
    resolve() {
      this.set('blocked', false);
      this.attrs.onResolve(this.get('request'));
    }
  }
});
