'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _TitleBar = require('../sections/TitleBar');

var _TitleBar2 = _interopRequireDefault(_TitleBar);

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

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

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

var _CreatePage2 = _interopRequireDefault(_CreatePage);

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

var _CreatePagePanel2 = _interopRequireDefault(_CreatePagePanel);

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

var serviceTypes = ['object', 'procedure', 'authority'];

var 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'
  }
});

var getRecordTypesByServiceType = function getRecordTypesByServiceType(recordTypes, perms, intl) {
  var recordTypesByServiceType = {};

  serviceTypes.forEach(function (serviceType) {
    var recordTypeNames = Object.keys(recordTypes).filter(function (recordTypeName) {
      var recordTypeConfig = recordTypes[recordTypeName];

      return recordTypeConfig.serviceConfig.serviceType === serviceType && !recordTypeConfig.disabled && (0, _permissionHelpers.canCreate)(recordTypeName, perms);
    }).sort(function (nameA, nameB) {
      var configA = recordTypes[nameA];
      var configB = recordTypes[nameB];

      // Primary sort by sortOrder

      var sortOrderA = configA.sortOrder;
      var 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

      var labelA = intl.formatMessage(configA.messages.record.name);
      var labelB = intl.formatMessage(configB.messages.record.name);

      // FIXME: This should be locale aware
      return labelA.localeCompare(labelB);
    });

    recordTypesByServiceType[serviceType] = recordTypeNames;
  });

  return recordTypesByServiceType;
};

var getVocabularies = function getVocabularies(recordTypeConfig, intl, getAuthorityVocabWorkflowState) {
  var recordTypeName = recordTypeConfig.name;
  var vocabularies = recordTypeConfig.vocabularies;


  var vocabularyNames = void 0;

  if (vocabularies) {
    vocabularyNames = Object.keys(vocabularies).filter(function (vocabularyName) {
      return vocabularyName !== 'all' && !(0, _workflowStateHelpers.isLocked)(getAuthorityVocabWorkflowState(recordTypeName, vocabularyName)) && !vocabularies[vocabularyName].disabled;
    }).sort(function (nameA, nameB) {
      var configA = vocabularies[nameA];
      var configB = vocabularies[nameB];

      // Primary sort by sortOrder

      var sortOrderA = configA.sortOrder;
      var 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

      var labelA = intl.formatMessage(configA.messages.name);
      var labelB = intl.formatMessage(configB.messages.name);

      // FIXME: This should be locale aware
      return labelA.localeCompare(labelB);
    });
  }

  return vocabularyNames;
};

var contextTypes = {
  config: _propTypes2.default.object
};

var propTypes = {
  intl: _reactIntl.intlShape,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  getAuthorityVocabWorkflowState: _propTypes2.default.func
};

var defaultProps = {
  getAuthorityVocabWorkflowState: function getAuthorityVocabWorkflowState() {
    return null;
  }
};

function CreatePage(props, context) {
  var intl = props.intl,
      perms = props.perms,
      getAuthorityVocabWorkflowState = props.getAuthorityVocabWorkflowState;
  var config = context.config;
  var recordTypes = config.recordTypes;


  var itemsByServiceType = {};
  var lists = [];

  if (recordTypes) {
    var recordTypesByServiceType = getRecordTypesByServiceType(recordTypes, perms, intl);

    serviceTypes.forEach(function (serviceType) {
      itemsByServiceType[serviceType] = recordTypesByServiceType[serviceType].map(function (recordType) {
        var recordTypeConfig = recordTypes[recordType];

        var vocabularies = getVocabularies(recordTypeConfig, intl, getAuthorityVocabWorkflowState);

        var vocabularyList = void 0;

        if (vocabularies && vocabularies.length > 0) {
          var vocabularyItems = vocabularies.map(function (vocabulary) {
            return _react2.default.createElement(
              'li',
              { key: vocabulary },
              _react2.default.createElement(
                _reactRouterDom.Link,
                { id: recordType + '/' + vocabulary, to: 'record/' + recordType + '/' + vocabulary },
                _react2.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.vocabularies[vocabulary].messages.name)
              )
            );
          });

          vocabularyList = _react2.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;
        }

        var recordDisplayName = _react2.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.messages.record.name);

        var recordLink = void 0;

        if (vocabularyList) {
          recordLink = _react2.default.createElement(
            'h3',
            { id: recordType },
            recordDisplayName
          );
        } else {
          recordLink = _react2.default.createElement(
            _reactRouterDom.Link,
            { id: recordType, to: 'record/' + recordType },
            recordDisplayName
          );
        }

        return _react2.default.createElement(
          'li',
          { key: recordType },
          recordLink,
          vocabularyList
        );
      });
    });

    serviceTypes.forEach(function (serviceType) {
      var items = itemsByServiceType[serviceType].filter(function (item) {
        return !!item;
      });

      if (items && items.length > 0) {
        lists.push(_react2.default.createElement(
          'div',
          { className: _CreatePagePanel2.default[serviceType], key: serviceType },
          _react2.default.createElement(
            'h2',
            null,
            _react2.default.createElement(_reactIntl.FormattedMessage, messages[serviceType])
          ),
          _react2.default.createElement(
            'ul',
            null,
            items
          )
        ));
      }
    });
  }

  var title = _react2.default.createElement(_reactIntl.FormattedMessage, messages.title);

  return _react2.default.createElement(
    'div',
    { className: _CreatePage2.default.common },
    _react2.default.createElement(_TitleBar2.default, { title: title, updateDocumentTitle: true }),
    _react2.default.createElement(
      'div',
      null,
      lists
    )
  );
}

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