import ApplicationSerializer from './application';
import { EXTENSION_ID_VERSION_SEPARATOR } from 'web-client/adapters/extension';

export default ApplicationSerializer.extend({
  extractId(modelClass, resourceHash) {
    let { id } = resourceHash.relationships.extension.data;
    let channelId = resourceHash.attributes.channel_id;
    return `${channelId}${EXTENSION_ID_VERSION_SEPARATOR}${id}`;
  },

  normalizeArrayResponse(store, type, payload, id, requestType) {
    let extensions = payload.extensions;
    let tokens = payload.tokens || [];
    let actives = payload.actives || [];
    let included = extensions.map(attributes => ({ type: 'extension', attributes }));
    let data = extensions.map(extension => {
      let clientId = extension.id;
      let version = extension.version;
      let attributes = { channel_id: payload.channel_id };
      let activation = actives.find(a => a.extension_id === clientId);
      if (activation) {
        attributes.active = true;
        try {
          attributes.config = JSON.parse(activation.config);
        } catch(e) {
          // eslint-disable-next-line no-console
          console.error(`Extension activated with invalid configuration: ${activation.config}`);
        }
      }

      let tokenEntry = tokens.find(t => t.extension_id === clientId);
      if (tokenEntry) {
        attributes.token = tokenEntry.token;
      }

      let relationships = {
        extension: {
          data: { type: 'extension', id: `${clientId}${EXTENSION_ID_VERSION_SEPARATOR}${version}` }
        }
      };

      return { type: 'extension-installation', attributes, relationships };
    });

    return this._super(store, type, { data, included }, id, requestType);
  }
});
