import ApplicationAdapter from 'web-client/adapters/application';
import { COLLECTION_BASE } from 'web-client/adapters/video-playlist';
import { stripPlaylistId } from 'web-client/utilities/video/playlist-item';

const COLLECTION_ITEMS_PATH_POSTFIX = 'items';

export default ApplicationAdapter.extend({
  apiVersion: 5,

  createRecord(store, type, snapshot) {
    let data = this.serialize(snapshot);
    let request = this.authRequest(
      `${COLLECTION_BASE}/${data.playlist}/${COLLECTION_ITEMS_PATH_POSTFIX}`,
      'post',
      { type: 'video', id: data.video }
    );
    // The create item endpoint does not return with the playlist id so we add it in
    request.then((response) => response.playlist_id = data.playlist);
    return request;
  },

  deleteRecord(store, type, snapshot) {
    let data = this.serialize(snapshot);
    return this.authRequest(
      `${COLLECTION_BASE}/${data.playlist}/${COLLECTION_ITEMS_PATH_POSTFIX}/${stripPlaylistId(snapshot.id)}`,
      'delete'
    );
  },
  updateRecord(store, type, snapshot) {
    let data = this.serialize(snapshot);
    return this.authRequest(
      `${COLLECTION_BASE}/${data.playlist}/${COLLECTION_ITEMS_PATH_POSTFIX}/${stripPlaylistId(snapshot.id)}`,
      'put',
      { position: data.position }
    );
  }
});
