import Ember from 'ember';
import ApplicationAdapter from './application';

const { inject } = Ember;

export default ApplicationAdapter.extend({
  api: inject.service(),

  updateRecord(store, type, snapshot) {
    let id = snapshot.id;
    let channelId = snapshot.record.get('channel.id');
    let vodIds = snapshot.record.get('vodIds').map((vodId) => {return parseInt(vodId);});
    // contentType and processData are explicitly set in the AJAX request due to
    // jQuery setting Content-Type to "x-www-form-urlencoded" by default and
    // automatically transforming data to query string params.
    // See also: models/offline-playlist-channel.js
    let options = {channelId: channelId, contentType: 'application/json; charset=UTF-8', processData: false};
    // jQuery refuses to send empty objects in the body without explicitly making them a string and saying they are json
    // It's possible to save an empty object for a playlist which we want to allow
    let data = JSON.stringify({playlist: {vod_ids: vodIds}});

    return this.get('api').request('put', `/api/playlists/channels/${channelId}/playlists/${id}`, data, options);
  },

  createRecord(store, type, snapshot) {
    let channelId = snapshot.record.get('channel.id'),
        vodIds = snapshot.record.get('vodIds').map((id) => {return parseInt(id);}),
        options = {contentType: "application/json; charset=UTF-8"},
        data = {playlist: {vod_ids: vodIds}};


    return this.get('api').request('post', `/api/playlists/channels/${channelId}/playlists`, JSON.stringify(data), options);
  },

  deleteRecord(store, type, snapshot) {
    let channelId = snapshot.record.get('channel.id'),
        id = snapshot.id;

    return this.get('api').request('del', `/api/playlists/channels/${channelId}/playlists/${id}`, {});
  }
});
