import ApplicationAdapter from './application';
import { EMS_API_VERSION, EMS_API_OPTIONS } from './extension';

export default ApplicationAdapter.extend({
  query(store, type, query) {
    if (query.channelId === undefined) {
      return {};
    }

    let channelId = encodeURIComponent(query.channelId);
    let path = `/v${EMS_API_VERSION}/channels/${channelId}/extensions`;
    return this.get('api').authRequest('get', path, '', EMS_API_OPTIONS).then(payload => {
      // Injecting channelId into the payload, since EMS doesn't return the value.
      payload.channel_id = query.channelId;
      return payload;
    });
  },

  createRecord(store, type, { record }) {
    let id = record.get('extension.clientId');
    let version = record.get('extension.version');
    let channelId = record.get('channelId');

    id = encodeURIComponent(id);
    version = encodeURIComponent(version);
    let path = `/v${EMS_API_VERSION}/channels/${channelId}/extensions/${id}/${version}`;
    return this.get('api').authRequest('post', path, '', EMS_API_OPTIONS);
  },

  updateRecord(store, type, { record }) {
    let id = record.get('extension.clientId');
    let version = record.get('extension.version');
    let channelId = record.get('channelId');
    let active = record.get('active');
    let config = active ? record.get('config') : {};

    // NOTE: Extension activation configuration is opaque to the EMS backend and encoded to a single string.
    config = JSON.stringify(config || {});

    id = encodeURIComponent(id);
    version = encodeURIComponent(version);
    let path = `/v${EMS_API_VERSION}/channels/${channelId}/extensions/${id}/${version}`;
    let data = JSON.stringify({ active, config });
    return this.get('api').authRequest('put', path, data, EMS_API_OPTIONS);
  },

  deleteRecord(store, type, { record }) {
    let id = record.get('extension.clientId');
    let version = record.get('extension.version');
    let channelId = record.get('channelId');

    id = encodeURIComponent(id);
    version = encodeURIComponent(version);
    let path = `/v${EMS_API_VERSION}/channels/${channelId}/extensions/${id}/${version}`;
    return this.get('api').authRequest('delete', path, '', EMS_API_OPTIONS);
  }
});
