'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findNarrowerRelations = exports.findBroaderRelation = exports.normalizeRelationList = exports.placeholderCsid = undefined;

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _cspaceRefname = require('cspace-refname');

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

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

// The placeholder csid accepted by the services layer happens to look like a js template string.
// eslint-disable-next-line no-template-curly-in-string
var placeholderCsid = exports.placeholderCsid = '${itemCSID}';

var normalizeRelationList = exports.normalizeRelationList = function normalizeRelationList(value) {
  if (!value) {
    return null;
  }

  if (_immutable2.default.List.isList(value)) {
    return value;
  }

  if (_immutable2.default.Map.isMap(value)) {
    return _immutable2.default.List.of(value);
  }

  return null;
};

var findBroaderRelation = exports.findBroaderRelation = function findBroaderRelation(csid, relations) {
  if (!relations) {
    return null;
  }

  if ((0, _csidHelpers.isUrnCsid)(csid)) {
    var shortId = (0, _csidHelpers.getUrnCsidShortId)(csid);

    return relations.find(function (relation) {
      return relation.get('predicate') === 'hasBroader' && (0, _cspaceRefname.getItemShortID)(relation.getIn(['subject', 'refName'])) === shortId;
    });
  }

  var subjectCsid = csid || placeholderCsid;

  return relations.find(function (relation) {
    return relation.get('predicate') === 'hasBroader' && relation.getIn(['subject', 'csid']) === subjectCsid;
  });
};

var findNarrowerRelations = exports.findNarrowerRelations = function findNarrowerRelations(csid, relations) {
  if (!relations) {
    return _immutable2.default.List();
  }

  var objectCsid = csid || placeholderCsid;

  return relations.filter(function (relation) {
    return relation.get('predicate') === '' || relation.get('predicate') === 'hasBroader' && relation.getIn(['object', 'csid']) === objectCsid;
  });
};