import on from 'ember-evented/on';
import Service from 'ember-service';
import { A as emberA } from 'ember-array/utils';
import injectService from 'ember-service/inject';

export default Service.extend({
  recommendedUsers: null,
  store: injectService(),
  session: injectService(),
  setDefaults: on('init', function () {
    this.set('recommendedUsers', emberA());
  }),

  fetchRecommendations() {
    let store = this.get('store');
    let { userData } = this.get('session');
    let login = userData ? userData.login : undefined;

    this.set('isLoading', true);

    store.query('friends-list-user', {
      login,
      type: 'recommended'
    }).then(results => {
      if (this.isDestroyed) { return; }
      let meta = results.get('meta');
      this.set('recommendedSource', meta.source || '');
      this.get('recommendedUsers').addObjects(results);
      this.set('isLoading', false);
    });
  },
  unrecommendUser(user) {
    let store = this.get('store');
    let login = this.get('session.userData.login');

    store.queryRecord('friends-list-user', {
      type: 'unrecommend',
      login,
      target: user.get('login')
    }).finally(() => {
      if (this.isDestroyed) { return; }
      this.get('recommendedUsers').removeObject(user);
    });
  },
  removeRecommendation(user) {
    this.get('recommendedUsers').removeObject(user);
  }
});
