'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.hasHierarchyRelations = exports.isRecordImmutable = exports.isSecurityRecordImmutable = exports.isRecordReplicated = exports.isRecordLocked = exports.isRecordDeprecated = exports.getWorkflowState = exports.isNewRecord = exports.isExistingRecord = exports.computeRecordData = exports.computeField = exports.validateRecordData = exports.validateField = exports.getCreatedUser = exports.getCreatedTimestamp = exports.getUpdatedUser = exports.getUpdatedTimestamp = exports.getRefName = exports.getCsid = exports.getCoreFieldValue = exports.prepareForSending = exports.setXmlNamespaceAttribute = exports.attributePropertiesToTop = exports.getDocument = exports.cloneRecordData = exports.clearUncloneable = exports.createRecordData = exports.applyDefaults = exports.spreadDefaultValue = exports.createBlankRecord = exports.normalizeRecordData = exports.normalizeFieldValue = exports.deepDelete = exports.deepSet = exports.deepGet = exports.getPartNSPropertyName = exports.getPart = exports.getPartPropertyName = exports.ERROR_KEY = exports.DOCUMENT_PROPERTY_NAME = exports.NS_PREFIX = undefined;

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

var _get2 = _interopRequireDefault(_get);

var _errorCodes = require('../constants/errorCodes');

var _configHelpers = require('./configHelpers');

var _csidHelpers = require('./csidHelpers');

var _workflowStateHelpers = require('./workflowStateHelpers');

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

function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }

const numericPattern = /^[0-9]$/;

const NS_PREFIX = exports.NS_PREFIX = 'ns2';
const DOCUMENT_PROPERTY_NAME = exports.DOCUMENT_PROPERTY_NAME = 'document';
const ERROR_KEY = exports.ERROR_KEY = '[error]';

const getPartPropertyName = exports.getPartPropertyName = partName => `${NS_PREFIX}:${partName}`;

const getPart = exports.getPart = (data, partName) => data.getIn([DOCUMENT_PROPERTY_NAME, getPartPropertyName(partName)]);

const getPartNSPropertyName = exports.getPartNSPropertyName = prefix => `@xmlns:${prefix}`;

/**
 * Deeply get a value in an Immutable.Map. This is similar to Immutable.Map.getIn, but differs in
 * one way:
 *
 * When a key of '0' is encountered, and that key is used to index a data item that is not a List,
 * the data item itself is returned. This accommodates data in which a list containing a single
 * item may be represented by that one item.
 */
const deepGet = exports.deepGet = (data, path) => {
  if (!Array.isArray(path) || path.length === 0) {
    throw new Error('path must be a non-empty array');
  }

  if (!data) {
    return undefined;
  }

  var _path = _toArray(path);

  const key = _path[0],
        rest = _path.slice(1);

  let value;

  if ((key === '0' || key === 0) && !_immutable2.default.List.isList(data)) {
    // Allow a key of 0 to refer to a single non-list value.
    value = data;
  } else {
    value = data.get(key);
  }

  if (!value || rest.length === 0) {
    return value;
  }

  return deepGet(value, rest);
};

/**
 * Deeply set a value in an Immutable.Map. This is similar to Immutable.Map.setIn, but differs in
 * two ways:
 *
 * When a non-existent key is encountered in the middle of a path, this function may create a List
 * or a Map at that location, depending on the key. If the key is a numeric string, a List is
 * created. Otherwise, a Map is created. Immutable.Map.setIn always creates a Map.
 *
 * This function also promotes an existing singular (non-List) item to a List, if any numeric key
 * is applied to it.
 */
const deepSet = exports.deepSet = (data, path, value) => {
  if (!Array.isArray(path) || path.length === 0) {
    throw new Error('path must be a non-empty array');
  }

  var _path2 = _toArray(path);

  const key = _path2[0],
        rest = _path2.slice(1);

  const isKeyNumeric = numericPattern.test(key);

  let normalizedData;

  if (data) {
    if (isKeyNumeric && !_immutable2.default.List.isList(data)) {
      // Promote a single (non-list) value into a list when a numeric key is supplied.
      normalizedData = _immutable2.default.List.of(data);
    } else {
      normalizedData = data;
    }
  } else if (isKeyNumeric) {
    normalizedData = _immutable2.default.List();
  } else {
    normalizedData = _immutable2.default.Map();
  }

  const resolvedValue = rest.length === 0 ? value : deepSet(normalizedData.get(key), rest, value);

  return normalizedData.set(key, resolvedValue);
};

/**
 * Deeply delete a value in an Immutable.Map. This is similar to Immutable.Map.deleteIn, but differs
 * in two ways:
 *
 * When a non-existent key is encountered in the middle of a path, this function may create a List
 * or a Map at that location, depending on the key. If the key is a numeric string, a List is
 * created. Otherwise, a Map is created. Immutable.Map.deleteIn makes no change when a key in the
 * path does not exist.
 *
 * This function also promotes an existing singular (non-List) item to a List, if any numeric key
 * is applied to it.
 */
const deepDelete = exports.deepDelete = (data, path) =>
// First call deepSet with undefined value to ensure the path exists. Then call deleteIn.
deepSet(data, path).deleteIn(path);

const normalizeFieldValue = exports.normalizeFieldValue = (fieldDescriptor, fieldValue, expandRepeating = true) => {
  let normalizedValue = fieldValue;

  if (fieldDescriptor && typeof fieldValue !== 'undefined') {
    if (_immutable2.default.Map.isMap(normalizedValue)) {
      normalizedValue = normalizedValue.map((childValue, childName) => normalizeFieldValue(fieldDescriptor[childName], childValue));
    } else if (_immutable2.default.List.isList(normalizedValue)) {
      normalizedValue = normalizedValue.map(instance => normalizeFieldValue(fieldDescriptor, instance, false));
    }

    if (expandRepeating && (0, _configHelpers.isFieldRepeating)(fieldDescriptor) && !_immutable2.default.List.isList(normalizedValue)) {
      normalizedValue = _immutable2.default.List.of(normalizedValue);
    }
  }

  return normalizedValue;
};

const normalizeRecordData = exports.normalizeRecordData = (recordTypeConfig, data) => {
  let normalizedData = normalizeFieldValue(recordTypeConfig.fields, data);

  if (recordTypeConfig.normalizeRecordData) {
    normalizedData = recordTypeConfig.normalizeRecordData(data, recordTypeConfig);
  }

  return normalizedData;
};

/**
 * Create a blank data record for a given CollectionSpace record type.
 */
const createBlankRecord = exports.createBlankRecord = recordTypeConfig => {
  const fields = recordTypeConfig.fields;


  const documentKey = Object.keys(fields)[0];
  const documentDescriptor = fields[documentKey];
  const document = {};

  // On some records, e.g. roles, the document has a namespace.

  const documentNsUri = (0, _get2.default)(documentDescriptor, [_configHelpers.configKey, 'service', 'ns']);

  if (documentNsUri) {
    const nsPrefix = documentKey.split(':', 2)[0];

    document[getPartNSPropertyName(nsPrefix)] = documentNsUri;
  }

  // Most records have parts with a namespace.

  const partKeys = Object.keys(documentDescriptor);

  partKeys.forEach(partKey => {
    const partDescriptor = documentDescriptor[partKey];
    const nsUri = (0, _get2.default)(partDescriptor, [_configHelpers.configKey, 'service', 'ns']);

    if (nsUri) {
      const nsPrefix = partKey.split(':', 2)[0];

      document[partKey] = {
        [getPartNSPropertyName(nsPrefix)]: nsUri
      };
    }
  });

  return _immutable2.default.fromJS({
    [documentKey]: document
  });
};

/**
 * Set a default value into record data. When declared on a repeating field, a default value will
 * be set on all instances of that field existing in the record data. If a repeating field has no
 * instances, a single instance will be created.
 */
const spreadDefaultValue = exports.spreadDefaultValue = (value, fieldDescriptorPath, data) => {
  if (!fieldDescriptorPath || fieldDescriptorPath.length === 0) {
    return typeof data === 'undefined' ? value : data;
  }

  let map;

  if (typeof data === 'undefined') {
    map = _immutable2.default.Map();
  } else if (_immutable2.default.Map.isMap(data)) {
    map = data;
  } else {
    return data;
  }

  var _fieldDescriptorPath = _toArray(fieldDescriptorPath);

  const key = _fieldDescriptorPath[0],
        rest = _fieldDescriptorPath.slice(1);

  const child = map.get(key);

  if (_immutable2.default.List.isList(child)) {
    return child.reduce((updatedData, instance, index) => updatedData.setIn([key, index], spreadDefaultValue(value, rest, instance)), map);
  }

  return map.set(key, spreadDefaultValue(value, rest, child));
};

/**
 * Set default values in record data.
 */
const applyDefaults = exports.applyDefaults = (fieldDescriptor, data) => (0, _configHelpers.getDefaults)(fieldDescriptor).reduce((updatedData, defaultDescriptor) => spreadDefaultValue(defaultDescriptor.value, defaultDescriptor.path, updatedData), data);

/**
 * Create a skeletal data record for a given CollectionSpace service.
 */
const createRecordData = exports.createRecordData = recordTypeConfig => applyDefaults(recordTypeConfig.fields, createBlankRecord(recordTypeConfig));

/**
 * Clear uncloneable fields from record data. Existing (not undefined) values in fields that are
 * not cloneable are set to the default value if one exists, or undefined otherwise.
 */
const clearUncloneable = exports.clearUncloneable = (fieldDescriptor, data) => {
  if (!fieldDescriptor) {
    return data;
  }

  if (typeof data !== 'undefined' && !(0, _configHelpers.isFieldCloneable)(fieldDescriptor)) {
    // If the field has been configured as not cloneable and there is an existing value, replace
    // the existing value with the default value if there is one, or undefined otherwise. The old
    // UI did not set uncloneable fields to the default value, but I think this was an oversight.

    return (0, _configHelpers.getDefaultValue)(fieldDescriptor);
  }

  if (_immutable2.default.Map.isMap(data)) {
    return data.reduce((updatedData, child, name) => updatedData.set(name, clearUncloneable(fieldDescriptor[name], child)), data);
  }

  if (_immutable2.default.List.isList(data)) {
    return data.reduce((updatedData, child, index) => updatedData.set(index, clearUncloneable(fieldDescriptor, child)), data);
  }

  return data;
};

/**
 * Create a new record as a clone of a given record.
 */
const cloneRecordData = exports.cloneRecordData = (recordTypeConfig, data) => {
  if (!data) {
    return data;
  }

  let clone = data;

  // Delete parts that should not exist in new records.

  clone = clone.deleteIn(['document', `${NS_PREFIX}:collectionspace_core`]);
  clone = clone.deleteIn(['document', `${NS_PREFIX}:account_permission`]);

  // Reset fields that are configured as not cloneable.

  clone = clearUncloneable(recordTypeConfig.fields, clone);

  return clone;
};

/**
 * Get the document from the data record.
 */
const getDocument = exports.getDocument = data => data.get(DOCUMENT_PROPERTY_NAME);

/**
 * Comparator function to sort properties that represent XML attributes and namespace declarations
 * (those that start with '@') to the top.
 */
const attributePropertiesToTop = exports.attributePropertiesToTop = (propertyNameA, propertyNameB) => {
  const firstCharA = propertyNameA.charAt(0);
  const firstCharB = propertyNameB.charAt(0);

  if (firstCharA === firstCharB) {
    return 0;
  }

  if (firstCharA === '@') {
    return -1;
  }

  if (firstCharB === '@') {
    return 1;
  }

  return 0;
};

/**
 * Set the XML namespace property on a document part if it is not set, using the URI defined in the
 * field configuration. This is used in the rare case that a record retrieved from the REST API did
 * not contain one of its expected parts; for example, when a schema extension is added to a record
 * type, the new part will not appear on existing records. If a field in that part was set through
 * the UI, the part will have been created, but without the namespace attribute, which is normally
 * created through the createBlankRecord function. That function would not have been called,
 * because this was not a new record. This function can be used before saving a record to ensure
 * that any missing namespace attributes get filled in.
 */
const setXmlNamespaceAttribute = exports.setXmlNamespaceAttribute = (partData, partName, partDescriptor) => {
  const nsUri = (0, _get2.default)(partDescriptor, [_configHelpers.configKey, 'service', 'ns']);

  var _partName$split = partName.split(':', 1),
      _partName$split2 = _slicedToArray(_partName$split, 1);

  const prefix = _partName$split2[0];


  if (prefix && nsUri) {
    const data = _immutable2.default.Map.isMap(partData) ? partData : _immutable2.default.Map();

    if (!data.get(`@xmlns:${prefix}`)) {
      return data.set(`@xmlns:${prefix}`, nsUri);
    }
  }

  return partData;
};

/**
 * Prepare record data for POST or PUT to the CollectionSpace REST API:
 *
 * - Document parts that may be present in data retrieved from the REST API, but that should not be
 *   present in data sent to the API, are removed.
 * - In the remaining parts, properties beginning with '@', which represent XML attributes and
 *   namespace declarations, are moved to the top. This is required by the REST API in order to
 *   properly translate the payload to XML.
 */
const prepareForSending = exports.prepareForSending = (data, recordTypeConfig) => {
  let preparedData = data;

  // Execute the prepareForSending function configured for the record type, if any.

  const customPrepareForSending = recordTypeConfig.prepareForSending;

  if (typeof customPrepareForSending === 'function') {
    preparedData = customPrepareForSending(preparedData, recordTypeConfig);
  }

  const documentName = preparedData.keySeq().first();

  let cspaceDocument = preparedData.get(documentName);

  // Filter out parts that don't need to be sent.
  // TODO: Use field configuration to determine what should be removed.

  cspaceDocument = cspaceDocument.filter((value, key) => key !== `${NS_PREFIX}:collectionspace_core` && key !== `${NS_PREFIX}:account_permission` && key !== `${NS_PREFIX}:image_metadata`);

  // Move XML attribute and namespace declaration properties (those that start with @) to the top,
  // since the REST API requires this.

  cspaceDocument = cspaceDocument.sortBy((value, name) => name, attributePropertiesToTop);

  // For each part, ensure XML namespace declaration properties are set, and move XML attribute and
  // namespace declaration properties to the top.

  if (documentName === 'document') {
    for (const key of cspaceDocument.keys()) {
      if (key.charAt(0) !== '@') {
        let part = cspaceDocument.get(key);

        part = setXmlNamespaceAttribute(part, key, (0, _get2.default)(recordTypeConfig, ['fields', documentName, key]));

        if (_immutable2.default.Map.isMap(part)) {
          part = part.sortBy((value, name) => name, attributePropertiesToTop);
        }

        cspaceDocument = cspaceDocument.set(key, part);
      }
    }
  }

  // Filter out hierarchy relations that don't have both a subject and an object, since the REST
  // API will error. These will occur when hierarchy autocomplete fields are emptied, or new
  // child instances are created but not filled in.

  // TODO: Move this to a computation in the HierarchyInput.

  const relations = cspaceDocument.getIn(['rel:relations-common-list', 'relation-list-item']);

  if (relations && _immutable2.default.List.isList(relations)) {
    const filteredRelations = relations.filter(relation => (relation.getIn(['object', 'refName']) || relation.getIn(['object', 'csid'])) && (relation.getIn(['subject', 'refName']) || relation.getIn(['subject', 'csid'])));

    cspaceDocument = cspaceDocument.setIn(['rel:relations-common-list', 'relation-list-item'], filteredRelations);
  }

  preparedData = preparedData.set(documentName, cspaceDocument);

  // Set to null any subrecord csid fields that don't contain valid csids -- these are pointing to
  // new subrecords that haven't been saved.

  const subrecords = recordTypeConfig.subrecords;


  if (subrecords) {
    Object.values(subrecords).forEach(subrecordConfig => {
      const csidField = subrecordConfig.csidField;


      if (csidField) {
        const subrecordCsid = deepGet(preparedData, csidField);

        if (!(0, _csidHelpers.isCsid)(subrecordCsid)) {
          preparedData = deepSet(preparedData, csidField, null);
        }
      }
    });
  }

  return preparedData;
};

const getCoreFieldValue = exports.getCoreFieldValue = (data, fieldName) => {
  if (data) {
    const corePart = getPart(data, 'collectionspace_core');

    if (corePart) {
      return corePart.get(fieldName);
    }
  }

  return undefined;
};

const getCsid = exports.getCsid = data => {
  if (!data) {
    return undefined;
  }

  const uri = data.getIn(['document', 'ns2:collectionspace_core', 'uri']);

  return uri ? uri.substring(uri.lastIndexOf('/') + 1) : undefined;
};

const getRefName = exports.getRefName = data => {
  if (!data) {
    return undefined;
  }

  return data.getIn(['document', 'ns2:collectionspace_core', 'refName']);
};

const getUpdatedTimestamp = exports.getUpdatedTimestamp = data => {
  let updatedAt = getCoreFieldValue(data, 'updatedAt');

  if (!updatedAt && data) {
    // Weird records like roles have updatedAt as a child of the root node.

    const doc = data.first();

    if (doc) {
      updatedAt = doc.get('updatedAt');
    }
  }

  return updatedAt;
};

const getUpdatedUser = exports.getUpdatedUser = data => getCoreFieldValue(data, 'updatedBy');

const getCreatedTimestamp = exports.getCreatedTimestamp = data => {
  let createdAt = getCoreFieldValue(data, 'createdAt');

  if (!createdAt) {
    // Weird records like roles have updatedAt as a child of the root node.

    const doc = data.first();

    if (doc) {
      createdAt = doc.get('createdAt');
    }
  }

  return createdAt;
};

const getCreatedUser = exports.getCreatedUser = data => getCoreFieldValue(data, 'createdBy');

const intPattern = /^-?\d+$/;
const floatPattern = /^-?(\d+(\.\d+)?|\.\d+)$/;
const datePattern = /^\d{4}-\d{2}-\d{2}(T00:00:00.000Z)?$/;
const dateTimePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;

const dataTypeValidators = {
  DATA_TYPE_MAP: value => _immutable2.default.Map.isMap(value),
  DATA_TYPE_STRING: () => true,
  DATA_TYPE_INT: value => intPattern.test(value),
  DATA_TYPE_FLOAT: value => floatPattern.test(value),
  DATA_TYPE_BOOL: value => typeof value === 'boolean' || value === 'true' || value === 'false',
  DATA_TYPE_DATE: value => datePattern.test(value),
  DATA_TYPE_DATETIME: value => dateTimePattern.test(value)
};

const validateDataType = (value, dataType) => {
  const validator = dataTypeValidators[dataType];

  return validator ? validator(value) : true;
};

const doValidate = (data, path = [], recordData, fieldDescriptor, expandRepeating = true) => {
  if (!fieldDescriptor) {
    return null;
  }

  const results = [];

  if (expandRepeating && (0, _configHelpers.isFieldRepeating)(fieldDescriptor)) {
    // This is a repeating field, and the expand flag is true. Validate each instance against the
    // current field descriptor.

    const instances = _immutable2.default.List.isList(data) ? data : _immutable2.default.List.of(data);

    instances.forEach((instance, index) => {
      const instanceData = instances.get(index);
      const instancePath = [...path, index];

      const instanceResults = doValidate(instanceData, instancePath, recordData, fieldDescriptor, false);

      if (instanceResults) {
        Array.prototype.push.apply(results, instanceResults);
      }
    });

    return results.length > 0 ? results : null;
  }

  const dataType = (0, _configHelpers.getFieldDataType)(fieldDescriptor);

  if (dataType === 'DATA_TYPE_MAP' && _immutable2.default.Map.isMap(data)) {
    // Validate this field's children, and add any child results to the results array.

    const childKeys = Object.keys(fieldDescriptor).filter(key => key !== _configHelpers.configKey);

    childKeys.forEach(childKey => {
      const childData = data ? data.get(childKey) : undefined;
      const childPath = [...path, childKey];
      const childFieldDescriptor = fieldDescriptor[childKey];

      const childResults = doValidate(childData, childPath, recordData, childFieldDescriptor);

      if (childResults) {
        Array.prototype.push.apply(results, childResults);
      }
    });
  }

  let result;

  // Check required.

  const required = (0, _configHelpers.isFieldRequired)(fieldDescriptor, recordData);

  // TODO: Does this make sense for compound fields?

  if (required && (typeof data === 'undefined' || data === null || data === '')) {
    result = {
      path,
      error: {
        code: _errorCodes.ERR_MISSING_REQ_FIELD,
        message: (0, _configHelpers.getRequiredMessage)(fieldDescriptor)
      }
    };
  }

  if (!result && typeof data !== 'undefined' && data !== null && data !== '') {
    // Check data type.

    if (!validateDataType(data, dataType)) {
      result = {
        path,
        error: {
          dataType,
          code: _errorCodes.ERR_DATA_TYPE,
          value: data
        }
      };
    }
  }

  if (!result) {
    // Custom validation.

    const customValidator = (0, _configHelpers.getFieldCustomValidator)(fieldDescriptor);

    if (customValidator) {
      const error = customValidator({ data, path, recordData, fieldDescriptor });

      if (error) {
        result = {
          path,
          error
        };
      }
    }
  }

  if (result) {
    results.push(result);
  }

  return results.length > 0 ? results : null;
};

const validateField = exports.validateField = (data, path, recordData, fieldDescriptor, expandRepeating) => {
  const validationResults = doValidate(data, path, recordData, fieldDescriptor, expandRepeating);

  if (validationResults) {
    // Validation results may either contain error objects, or promises that will resolve to error
    // objects (when the validation function was async). Wait for all of the promises to resolve.

    return Promise.all(validationResults.map(result => result.error)).then(resolvedErrors => {
      // Convert the resolved error array into a tree of errors.

      let errorTree = _immutable2.default.Map();

      resolvedErrors.forEach((error, index) => {
        if (error) {
          const errorPath = [...validationResults[index].path, ERROR_KEY];

          errorTree = deepSet(errorTree, errorPath, _immutable2.default.Map(error));
        }
      });

      return Promise.resolve(errorTree.size > 0 ? errorTree : null);
    }).catch(() => {
      // Something went wrong in an async validator. Set an error on the document.

      const errorTree = _immutable2.default.fromJS({
        document: {
          [ERROR_KEY]: {
            code: _errorCodes.ERR_UNABLE_TO_VALIDATE
          }
        }
      });

      return Promise.resolve(errorTree);
    });
  }

  return Promise.resolve(null);
};

const validateRecordData = exports.validateRecordData = (data, recordTypeConfig) => validateField(data, [], data, (0, _get2.default)(recordTypeConfig, 'fields'));

const doCompute = (data, path = [], recordData, subrecordData, fieldDescriptor, expandRepeating = true) => {
  if (!fieldDescriptor) {
    return undefined;
  }

  const results = [];

  if (expandRepeating && (0, _configHelpers.isFieldRepeating)(fieldDescriptor)) {
    // This is a repeating field, and the expand flag is true. Compute each instance.

    const instances = _immutable2.default.List.isList(data) ? data : _immutable2.default.List.of(data);

    instances.forEach((instance, index) => {
      const instanceData = instances.get(index);
      const instancePath = [...path, index];

      const instanceResults = doCompute(instanceData, instancePath, recordData, subrecordData, fieldDescriptor, false);

      if (instanceResults) {
        Array.prototype.push.apply(results, instanceResults);
      }
    });

    return results.length > 0 ? results : undefined;
  }

  const dataType = (0, _configHelpers.getFieldDataType)(fieldDescriptor);

  if (dataType === 'DATA_TYPE_MAP' && _immutable2.default.Map.isMap(data)) {
    // Compute this field's children, and add any child results to the results array.

    const childKeys = Object.keys(fieldDescriptor).filter(key => key !== _configHelpers.configKey);

    childKeys.forEach(childKey => {
      const childData = data ? data.get(childKey) : undefined;
      const childPath = [...path, childKey];
      const childFieldDescriptor = fieldDescriptor[childKey];

      const childResults = doCompute(childData, childPath, recordData, subrecordData, childFieldDescriptor);

      if (childResults) {
        Array.prototype.push.apply(results, childResults);
      }
    });
  }

  let result;

  const computer = (0, _configHelpers.getFieldComputer)(fieldDescriptor);

  if (computer) {
    let value;

    try {
      value = computer({ data, path, recordData, subrecordData, fieldDescriptor });
    } catch (error) {
      value = Promise.reject(error);
    }

    if (typeof value !== 'undefined') {
      result = {
        path,
        value
      };
    }
  }

  if (result) {
    results.push(result);
  }

  return results.length > 0 ? results : undefined;
};

const computeField = exports.computeField = (data, path, recordData, subrecordData, fieldDescriptor, expandRepeating = true) => {
  const computationResults = doCompute(data, path, recordData, subrecordData, fieldDescriptor, expandRepeating);

  if (typeof computationResults !== 'undefined') {
    // Computation results may either contain values, or promises that will resolve to values
    // (when the computation function was async). Wait for all of the promises to resolve.

    return Promise.all(computationResults.map(result => result.value)).then(resolvedValues => {
      // Convert the resolved value array into a tree of values.

      let valueTree = _immutable2.default.Map();

      resolvedValues.forEach((value, index) => {
        if (typeof value !== 'undefined') {
          const valuePath = computationResults[index].path;

          if (valuePath && valuePath.length > 0 && expandRepeating) {
            const prevValue = valueTree.getIn(valuePath);
            const nextValue = prevValue ? prevValue.mergeDeep(value) : value;

            valueTree = deepSet(valueTree, valuePath, nextValue);
          } else {
            valueTree = value;
          }
        }
      });

      return Promise.resolve(valueTree);
    })
    // Don't catch rejections, just let the caller handle them.
    ;
  }

  return Promise.resolve(undefined);
};

const computeRecordData = exports.computeRecordData = (data, subrecordData, recordTypeConfig) => computeField(data, [], data, subrecordData, (0, _get2.default)(recordTypeConfig, 'fields'));

const isExistingRecord = exports.isExistingRecord = data => !!(
// TODO: Move this into record type config.

data && (data.getIn(['document', 'ns2:collectionspace_core', 'uri']) || data.getIn(['ns2:role', '@csid']) || data.getIn(['ns2:accounts_common', '@csid'])));

const isNewRecord = exports.isNewRecord = data => !isExistingRecord(data);

const getWorkflowState = exports.getWorkflowState = data => data ? data.getIn(['document', 'ns2:collectionspace_core', 'workflowState']) : undefined;

const isRecordDeprecated = exports.isRecordDeprecated = data => (0, _workflowStateHelpers.isDeprecated)(getWorkflowState(data));

const isRecordLocked = exports.isRecordLocked = data => (0, _workflowStateHelpers.isLocked)(getWorkflowState(data));

const isRecordReplicated = exports.isRecordReplicated = data => (0, _workflowStateHelpers.isReplicated)(getWorkflowState(data));

const isSecurityRecordImmutable = exports.isSecurityRecordImmutable = data => {
  // Accounts and roles have the concept of "immutability", which is basically the same as
  // locked.

  if (data) {
    const doc = data.first();

    return doc && (doc.get('permsProtection') === 'immutable' || doc.get('rolesProtection') === 'immutable');
  }

  return false;
};

const isRecordImmutable = exports.isRecordImmutable = data => isRecordLocked(data) || isRecordDeprecated(data) || isRecordReplicated(data) || isSecurityRecordImmutable(data);

const hasHierarchyRelations = exports.hasHierarchyRelations = data => {
  const items = data.getIn(['document', 'rel:relations-common-list', 'relation-list-item']);

  return !!items && (!_immutable2.default.List.isList(items) || items.size > 0);
};