import ApplicationAdapter from './application';
import env from 'web-client/config/environment';

export const EMS_API_VERSION = 5;
export const EXTENSION_ID_VERSION_SEPARATOR = '-';

export const EMS_API_OPTIONS = {
  host: env.extensionsHost,
  version: EMS_API_VERSION,
  contentType: 'application/json'
};

export default ApplicationAdapter.extend({
  _parseId(compositeId) {
    let [ id, version ] = compositeId.split(EXTENSION_ID_VERSION_SEPARATOR);
    return {
      id,
      version
    };
  },

  _setActiveState(store, extId, channelId, active, config) {
    let { id, version } = this._parseId(extId);
    id = encodeURIComponent(id);
    version = encodeURIComponent(version);
    let api = this.get('api');
    let path = `/v${EMS_API_VERSION}/channels/${channelId}/extensions/${id}/${version}`;

    // NOTE: Extension activation configuration is opaque to the EMS backend and encoded to a single string.
    config = JSON.stringify(config || {});
    let data = JSON.stringify({ active, config });
    return api.authRequest('put', path, data, EMS_API_OPTIONS);
  },

  findRecord(store, type, compositeId) {
    let { id, version } = this._parseId(compositeId);
    id = encodeURIComponent(id);
    version = encodeURIComponent(version);
    let api = this.get('api');
    let path = `/v${EMS_API_VERSION}/extensions/${id}/${version}`;
    return api.authRequest('get', path, '', EMS_API_OPTIONS);
  },

  findAll() {
    let api = this.get('api');
    let path = `/v${EMS_API_VERSION}/extensions`;
    return api.authRequest('get', path, '', EMS_API_OPTIONS);
  },

  query(store, type, query) {
    if (query.channelId === undefined) {
      return {};
    }

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