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

export default Component.extend({
  store: injectService(),
  session: injectService(),
  tracking: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  api: injectService('twitch-friends-list/api'),
  settings: storageFor('twitch-friend-settings'),
  showBalloon: false,
  load: true,
  classNames: ['friend-button', 'js-friend-button'],
  userId: null,
  user: null,

  _setUser() {
    if (this.isDestroyed) {
      return;
    }
    let id = this.get('userId');
    let store = this.get('store');
    let user = store.peekRecord('friends-list-user', id);
    this.set('user', user);
  },

  didReceiveAttrs() {
    this._super(...arguments);
    let login = this.get('userLogin');

    if (this.get('user') || !login) {
      return;
    }

    if (this.get('load')) {
      this.get('api').initializeFriendButton(login).then(() => {
        this._setUser();
      });
    } else {
      this._setUser();
    }
  },

  _respondToRequest(action) {
    let store = this.get('store'),
        requests = this.get('requests'),
        userId = this.get('userId'),
        request = store.peekRecord('friends-list-request', userId);

    return requests[action](request);
  },

  actions: {
    toggleBalloon() {
      this.set('showBalloon', !this.get('showBalloon'));
    },

    openLogin() {
      if (libs.login) {
        libs.login();
      }
    },

    addFriend() {
      let store = this.get('store');
      let friendId = this.get('userId');
      let friendLogin = this.get('userLogin');

      store.createRecord('friends-list-request', {
        friendId,
        friendLogin
      }).save().then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let userId = this.get('user.id');
        this.get('tracking').trackEvent({
          event: 'friend_request',
          data: {
            request_id: `${sessionId}-${userId}`,
            login: this.get('session.userData.login'),
            target_login: friendLogin,
            ui_context: this.get('uiContext')
          }
        });
      });
    },

    removeFriend() {
      let store = this.get('store'),
          login = this.get('user.login'),
          id = this.get('userId');

      store.queryRecord('friends-list-user', {
        type: 'unfriend',
        id,
        login
      }).then(() => {
        if (this.isDestroyed) { return; }
        this.get('tracking').trackEvent({
          event: 'friend_remove',
          data: {
            login: this.get('session.userData.login'),
            target_login: this.get('user.login'),
            reason: 'manual',
            ui_context: this.get('uiContext')
          }
        });
      });
    },

    acceptRequest() {
      this.set('settings.onboardingDismissed', true);
      this._respondToRequest('accept').then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let friendId = this.get('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('user.login'),
            ui_context: this.get('uiContext')
          }
        });
      });
    },

    rejectRequest() {
      this._respondToRequest('reject').then(() => {
        if (this.isDestroyed) { return; }
        let sessionId = this.get('session.userData.id');
        let friendId = this.get('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('user.login'),
            ui_context: this.get('uiContext')
          }
        });
      });
    }
  }
});
