import injectService from 'ember-service/inject';
import Component from 'ember-component';
import computed from 'ember-computed';
import { storageFor } from 'ember-local-storage';

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

  user: null,
  session: injectService(),
  store: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  tracking: injectService(),
  settings: storageFor('twitch-friend-settings'),
  isError: false,

  isSelf: computed('user', function() {
    if (this.get('user')) {
      return this.get('user.id') === this.get('session.userData.id').toString();
    }
    return false;
  }),

  _addFriend(user) {
    return this.get('store').createRecord('friends-list-request', {
      friendId: user.get('id'),
      friendLogin: user.get('login')
    }).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: 'search'
        }
      });
    }).catch(() => {
      this.set('isError', true);
    });
  },

  _acceptFriend(user) {
    let store = this.get('store'),
        id = user.get('id'),
        request = store.peekRecord('friends-list-request', id);

    if (!request) {
      throw new Error('Could not find request.');
    }
    return this.get('requests').accept(request);
  },

  _rejectFriend(user) {
    let store = this.get('store'),
        id = user.get('id'),
        request = store.peekRecord('friends-list-request', id);

    this.set('didRequest', false);
    if (request) {
      return this.get('requests').reject(request);
    }
    throw new Error('Could not find request.');
  },

  actions: {
    addFriend(user) {
      let store = this.get('store'),
          friendId = user.get('id'),
          friendLogin = user.get('login');

      this.set('didRequest', true);
      this.set('settings.onboardingDismissed', true);
      store.queryRecord('friends-list-user', {
        type: 'friend-status',
        id: friendId,
        login: friendLogin
      }).then(friend => {
        if (friend.get('isRequested')) {
          // Already requested them, so nothing left to do.
          return;
        }

        if (friend.get('isRequestedBy')) {
          return this._acceptFriend(friend);
        } else if (!friend.get('isFriend')) {
          return this._addFriend(friend);
        }
      }).catch(() => {
        this.set('isError', true);
      });
    },

    rejectFriend(user) {
      let store = this.get('store');
      let friendId = user.get('id');
      let friendLogin = user.get('login');

      this.set('settings.onboardingDismissed', true);
      store.queryRecord('friends-list-user', {
        type: 'friend-status',
        id: friendId,
        login: friendLogin
      }).then(rejected => {
        if (this.isDestroyed) { return; }
        if (rejected.get('isRequested') || rejected.get('didRequest')) {
          return this._rejectFriend(rejected);
        }
      }).catch(() => {
        this.set('isError', true);
      });
    }
  }
});
