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

export default Component.extend({
  user: null,
  session: injectService(),
  store: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  tracking: injectService(),
  settings: storageFor('twitch-friend-settings'),
  isError: 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'
        }
      });
      this.set('didRequest', true);
    });
  },

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

    if (request) {
      return this.get('requests').accept(request);
    }
    throw new Error('Could not find 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(friend) {
      let store = this.get('store');
      let friendId = friend.get('id');
      let friendLogin = friend.get('login');

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

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

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

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