import ApplicationAdapter from './application';

function getURL(id) {
  return `users/:login/follows/channels/${id}`;
}

function normalizeData(data, id, isFollowing) {
  data.id = id;
  data.is_following = isFollowing;
  return data;
}

export default ApplicationAdapter.extend({
  findRecord(store, type, id) {
    let url = getURL(id);
    return this.request(url).then(data => {
      return normalizeData(data, id, true);
    }, xhr => {
      // 404 taken to mean there is no follow
      // front-end components expect an object with isFollowing = false
      if (xhr.status === 404) {
        return {
          id,
          is_following: false
        };
      }

      throw xhr;
    });
  },

  updateRecord(store, type, snapshot) {
    let id = snapshot.id;
    let url = getURL(id);
    let isFollowing = snapshot.attr('isFollowing');
    let method = isFollowing ? 'put' : 'del';

    let payload = { notifications: snapshot.attr('notifications') };

    // Unfollowing is done with a DELETE, however the front-end
    // components expects the model to remain with the isFollowing set to false
    return this.authRequest(url, method, payload).then(data => {
      data = data || {}; // data can be empty when unfollowing
      return normalizeData(data, id, isFollowing);
    });
  },

  createRecord(store, type, snapshot) {
    let id = snapshot.id;
    let url = getURL(id);
    return this.authRequest(url, 'put').then(data => {
      return normalizeData(data, id, true);
    });
  }
});
