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

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.vocabularies;


  let vocabularyNames;

  if (vocabularies) {
    vocabularyNames = Object.keys(vocabularies).filter(vocabularyName => vocabularyName !== 'all' && !(0, _workflowStateHelpers.isLocked)(getAuthorityVocabWorkflowState(recordTypeName, vocabularyName)) && !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: _propTypes2.default.object
};

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

const defaultProps = {
  getAuthorityVocabWorkflowState: () => null
};

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


  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 => _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;
        }

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

        let recordLink;

        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(serviceType => {
      const items = itemsByServiceType[serviceType].filter(item => !!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
          )
        ));
      }
    });
  }

  const 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;