'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

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

var _cspaceInput = require('cspace-input');

var _RecordFormSelector = require('../../../styles/cspace-ui/RecordFormSelector.css');

var _RecordFormSelector2 = _interopRequireDefault(_RecordFormSelector);

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

const DropdownMenuInput = _cspaceInput.baseComponents.DropdownMenuInput;


const formOptions = (forms, intl) => Object.keys(forms).filter(formName => !forms[formName].disabled).sort((nameA, nameB) => {
  const configA = forms[nameA];
  const configB = forms[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);
}).map(formName => ({
  label: intl.formatMessage(forms[formName].messages.name),
  value: formName
}));

const propTypes = {
  config: _propTypes2.default.object,
  intl: _reactIntl.intlShape,
  formName: _propTypes2.default.string,
  recordType: _propTypes2.default.string,
  onCommit: _propTypes2.default.func
};

function RecordFormSelector(props) {
  const config = props.config,
        intl = props.intl,
        formName = props.formName,
        recordType = props.recordType,
        onCommit = props.onCommit;


  const forms = (0, _get2.default)(config, ['recordTypes', recordType, 'forms']);

  if (!forms || Object.keys(forms).length < 2) {
    return null;
  }

  const options = formOptions(forms, intl);

  if (options.length < 2) {
    return null;
  }

  return _react2.default.createElement(
    'div',
    { className: _RecordFormSelector2.default.common },
    _react2.default.createElement(DropdownMenuInput, {
      options: options,
      value: formName,
      onCommit: onCommit
    })
  );
}

RecordFormSelector.propTypes = propTypes;

exports.default = (0, _reactIntl.injectIntl)(RecordFormSelector);