"use strict";

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

var _immutable = _interopRequireDefault(require("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
const placeholderCsid = '${itemCSID}';
exports.placeholderCsid = placeholderCsid;

const normalizeRelationList = value => {
  if (!value) {
    return null;
  }

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

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

  return null;
};

exports.normalizeRelationList = normalizeRelationList;

const findBroaderRelation = (csid, relations) => {
  if (!relations) {
    return null;
  }

  if ((0, _csidHelpers.isUrnCsid)(csid)) {
    const shortId = (0, _csidHelpers.getUrnCsidShortId)(csid);
    return relations.find(relation => relation.get('predicate') === 'hasBroader' && (0, _cspaceRefname.getItemShortID)(relation.getIn(['subject', 'refName'])) === shortId);
  }

  const subjectCsid = csid || placeholderCsid;
  return relations.find(relation => relation.get('predicate') === 'hasBroader' && relation.getIn(['subject', 'csid']) === subjectCsid);
};

exports.findBroaderRelation = findBroaderRelation;

const findNarrowerRelations = (csid, relations) => {
  if (!relations) {
    return _immutable.default.List();
  }

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

exports.findNarrowerRelations = findNarrowerRelations;