"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = CreatePage;

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactIntl = require("react-intl");

var _reactRouterDom = require("react-router-dom");

var _immutable = _interopRequireDefault(require("immutable"));

var _TitleBar = _interopRequireDefault(require("../sections/TitleBar"));

var _permissionHelpers = require("../../helpers/permissionHelpers");

var _workflowStateHelpers = require("../../helpers/workflowStateHelpers");

var _CreatePage = _interopRequireDefault(require("../../../styles/cspace-ui/CreatePage.css"));

var _CreatePagePanel = _interopRequireDefault(require("../../../styles/cspace-ui/CreatePagePanel.css"));

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

const serviceTypes = ['object', 'procedure', 'authority'];
const messages = (0, _reactIntl.defineMessages)({
  title: {
    "id": "createPage.title",
    "defaultMessage": "Create New"
  },
  object: {
    "id": "createPage.object",
    "defaultMessage": "Objects"
  },
  procedure: {
    "id": "createPage.procedure",
    "defaultMessage": "Procedures"
  },
  authority: {
    "id": "createPage.authority",
    "defaultMessage": "Authorities"
  }
});

const getRecordTypesByServiceType = (recordTypes, perms, intl) => {
  const recordTypesByServiceType = {};
  serviceTypes.forEach(serviceType => {
    const recordTypeNames = Object.keys(recordTypes).filter(recordTypeName => {
      const recordTypeConfig = recordTypes[recordTypeName];
      return recordTypeConfig.serviceConfig.serviceType === serviceType && !recordTypeConfig.disabled && (0, _permissionHelpers.canCreate)(recordTypeName, perms);
    }).sort((nameA, nameB) => {
      const configA = recordTypes[nameA];
      const configB = recordTypes[nameB]; // Primary sort by sortOrder

      let sortOrderA = configA.sortOrder;
      let sortOrderB = configB.sortOrder;

      if (typeof sortOrderA !== 'number') {
        sortOrderA = Number.MAX_VALUE;
      }

      if (typeof sortOrderB !== 'number') {
        sortOrderB = Number.MAX_VALUE;
      }

      if (sortOrderA !== sortOrderB) {
        return sortOrderA > sortOrderB ? 1 : -1;
      } // Secondary sort by label


      const labelA = intl.formatMessage(configA.messages.record.name);
      const labelB = intl.formatMessage(configB.messages.record.name); // FIXME: This should be locale aware

      return labelA.localeCompare(labelB);
    });
    recordTypesByServiceType[serviceType] = recordTypeNames;
  });
  return recordTypesByServiceType;
};

const getVocabularies = (recordTypeConfig, intl, getAuthorityVocabWorkflowState) => {
  const recordTypeName = recordTypeConfig.name;
  const {
    vocabularies
  } = recordTypeConfig;
  let vocabularyNames;

  if (vocabularies) {
    vocabularyNames = Object.keys(vocabularies).filter(vocabularyName => {
      // Filter out vocabularies that don't exist in the services layer, vocabularies that are
      // locked, and vocabularies that are disabled. Always include the 'all' vocabulary.
      const workflowState = getAuthorityVocabWorkflowState(recordTypeName, vocabularyName);
      return vocabularyName !== 'all' && workflowState // Empty workflow state means vocab doesn't exist.
      && !(0, _workflowStateHelpers.isLocked)(workflowState) && !vocabularies[vocabularyName].disabled;
    }).sort((nameA, nameB) => {
      const configA = vocabularies[nameA];
      const configB = vocabularies[nameB]; // Primary sort by sortOrder

      let sortOrderA = configA.sortOrder;
      let sortOrderB = configB.sortOrder;

      if (typeof sortOrderA !== 'number') {
        sortOrderA = Number.MAX_VALUE;
      }

      if (typeof sortOrderB !== 'number') {
        sortOrderB = Number.MAX_VALUE;
      }

      if (sortOrderA !== sortOrderB) {
        return sortOrderA > sortOrderB ? 1 : -1;
      } // Secondary sort by label


      const labelA = intl.formatMessage(configA.messages.name);
      const labelB = intl.formatMessage(configB.messages.name); // FIXME: This should be locale aware

      return labelA.localeCompare(labelB);
    });
  }

  return vocabularyNames;
};

const contextTypes = {
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  })
};
const propTypes = {
  intl: _reactIntl.intlShape,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  getAuthorityVocabWorkflowState: _propTypes.default.func
};
const defaultProps = {
  getAuthorityVocabWorkflowState: () => null
};

function CreatePage(props, context) {
  const {
    intl,
    perms,
    getAuthorityVocabWorkflowState
  } = props;
  const {
    config
  } = context;
  const {
    recordTypes
  } = config;
  const itemsByServiceType = {};
  const lists = [];

  if (recordTypes) {
    const recordTypesByServiceType = getRecordTypesByServiceType(recordTypes, perms, intl);
    serviceTypes.forEach(serviceType => {
      itemsByServiceType[serviceType] = recordTypesByServiceType[serviceType].map(recordType => {
        const recordTypeConfig = recordTypes[recordType];
        const vocabularies = getVocabularies(recordTypeConfig, intl, getAuthorityVocabWorkflowState);
        let vocabularyList;

        if (vocabularies && vocabularies.length > 0) {
          const vocabularyItems = vocabularies.map(vocabulary => /*#__PURE__*/_react.default.createElement("li", {
            key: vocabulary
          }, /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
            id: `${recordType}/${vocabulary}`,
            to: `/record/${recordType}/${vocabulary}`
          }, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.vocabularies[vocabulary].messages.name))));
          vocabularyList = /*#__PURE__*/_react.default.createElement("ul", null, vocabularyItems);
        }

        if (recordTypeConfig.vocabularies && !vocabularyList) {
          // The record type is an authority, but no vocabularies are enabled. Don't render
          // anything.
          return null;
        }

        const recordDisplayName = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.messages.record.name);

        let recordLink;

        if (vocabularyList) {
          recordLink = /*#__PURE__*/_react.default.createElement("h3", {
            id: recordType
          }, recordDisplayName);
        } else {
          recordLink = /*#__PURE__*/_react.default.createElement(_reactRouterDom.Link, {
            id: recordType,
            to: `/record/${recordType}`
          }, recordDisplayName);
        }

        return /*#__PURE__*/_react.default.createElement("li", {
          key: recordType
        }, recordLink, vocabularyList);
      });
    });
    serviceTypes.forEach(serviceType => {
      const items = itemsByServiceType[serviceType].filter(item => !!item);

      if (items && items.length > 0) {
        lists.push( /*#__PURE__*/_react.default.createElement("div", {
          className: _CreatePagePanel.default[serviceType],
          key: serviceType
        }, /*#__PURE__*/_react.default.createElement("h2", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages[serviceType])), /*#__PURE__*/_react.default.createElement("ul", null, items)));
      }
    });
  }

  const title = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.title);

  return /*#__PURE__*/_react.default.createElement("div", {
    className: _CreatePage.default.common
  }, /*#__PURE__*/_react.default.createElement(_TitleBar.default, {
    title: title,
    updateDocumentTitle: true
  }), /*#__PURE__*/_react.default.createElement("div", null, lists));
}

CreatePage.propTypes = propTypes;
CreatePage.defaultProps = defaultProps;
CreatePage.contextTypes = contextTypes;