'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getBatchName = exports.getReportName = exports.createInvocationData = undefined;

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _set = require('lodash/set');

var _set2 = _interopRequireDefault(_set);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const prepareInvocationContext = (invocationContext, params) => {
  if (params) {
    const paramPairs = Object.keys(params).map(key => ({
      key,
      value: params[key]
    }));

    if (paramPairs.length > 0) {
      (0, _set2.default)(invocationContext, ['params', 'param'], paramPairs);
    }
  }

  return invocationContext;
};

const createInvocationData = exports.createInvocationData = (config, invocationDescriptor, type, name) => {
  const params = invocationDescriptor.params,
        recordType = invocationDescriptor.recordType,
        invocationCsid = invocationDescriptor.csid;


  const docType = (0, _get2.default)(config, ['recordTypes', recordType, 'serviceConfig', 'objectName']);

  let invocationContext = {
    docType
  };

  if (invocationCsid === null || typeof invocationCsid === 'undefined') {
    invocationContext.mode = 'nocontext';
  } else if (Array.isArray(invocationCsid)) {
    invocationContext.mode = 'list';
    invocationContext.listCSIDs = { csid: invocationCsid };
  } else {
    invocationContext.mode = 'single';
    invocationContext.singleCSID = invocationCsid;
  }

  const prepare = (0, _get2.default)(config, ['invocables', type, name, 'prepareInvocationContext']) || prepareInvocationContext;

  invocationContext = prepare(invocationContext, params);

  return {
    'ns2:invocationContext': Object.assign({
      '@xmlns:ns2': 'http://collectionspace.org/services/common/invocable'
    }, invocationContext)
  };
};

const getReportName = exports.getReportName = reportItem => {
  const filename = reportItem && reportItem.get('filename');
  let name = filename;

  if (filename) {
    const dotIndex = filename.lastIndexOf('.');

    if (dotIndex >= 0) {
      name = filename.substring(0, dotIndex);
    }
  }

  return name;
};

const getBatchName = exports.getBatchName = batchItem => batchItem && batchItem.get('name');