"use strict";

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

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

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

var _get = _interopRequireDefault(require("lodash/get"));

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

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

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

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

const {
  DropdownMenuInput
} = _cspaceInput.baseComponents;

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: _propTypes.default.object,
  intl: _reactIntl.intlShape,
  formName: _propTypes.default.string,
  recordType: _propTypes.default.string,
  onCommit: _propTypes.default.func
};

function RecordFormSelector(props) {
  const {
    config,
    intl,
    formName,
    recordType,
    onCommit
  } = props;
  const forms = (0, _get.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 _react.default.createElement("div", {
    className: _RecordFormSelector.default.common
  }, _react.default.createElement(DropdownMenuInput, {
    options: options,
    value: formName,
    onCommit: onCommit
  }));
}

RecordFormSelector.propTypes = propTypes;

var _default = (0, _reactIntl.injectIntl)(RecordFormSelector);

exports.default = _default;