"use strict";

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

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

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

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

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

var _configContextInputs = require("../../../helpers/configContextInputs");

var _configHelpers = require("../../../helpers/configHelpers");

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

const propTypes = {
  config: _propTypes.default.shape({
    locale: _propTypes.default.string
  }).isRequired,
  name: _propTypes.default.string,
  placeholder: _propTypes.default.string,
  readOnly: _propTypes.default.bool,
  recordType: _propTypes.default.string,
  rootPath: _propTypes.default.string,
  value: _propTypes.default.string,
  valueDescriptor: _propTypes.default.shape({
    [_configHelpers.configKey]: _propTypes.default.object
  }),
  onCommit: _propTypes.default.func
};

function GroupInput(props) {
  const {
    config,
    name,
    placeholder,
    readOnly,
    recordType,
    rootPath,
    value,
    valueDescriptor,
    onCommit
  } = props;

  if (readOnly) {
    let message;

    if (valueDescriptor) {
      const rootPathParts = rootPath ? rootPath.split('/') : [];
      const pathParts = value ? value.split('/') : [];
      const messages = (0, _get.default)(valueDescriptor, [_configHelpers.configKey, 'messages']);

      if (messages) {
        const level = pathParts.length - rootPathParts.length;

        if (level > 1) {
          // Prefer the fullName message.
          message = messages.fullName;
        } else {
          // This is a top-level group in a group. Prefer the groupName message.
          message = messages.groupName;
        }

        if (!message) {
          message = messages.name || messages.fullName;
        }
      }
    }

    return message ? /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, message) : /*#__PURE__*/_react.default.createElement("span", null, value);
  } // let pathFilter;
  // if (rootPath) {
  //   pathFilter = option => (option.value.startsWith(rootPath) && (option.value !== rootPath));
  // }


  const sortComparator = (optionA, optionB) => {
    const labelA = optionA.label;
    const labelB = optionB.label;
    return labelA.localeCompare(labelB, config.locale, {
      sensitivity: 'base'
    });
  };

  return /*#__PURE__*/_react.default.createElement(_configContextInputs.OptionPickerInput, {
    blankable: false,
    name: name,
    placeholder: placeholder // prefilter={pathFilter}
    ,
    source: (0, _configHelpers.getRecordGroupOptionListName)(recordType, rootPath),
    value: value,
    sortComparator: sortComparator,
    onCommit: onCommit
  });
}

GroupInput.propTypes = propTypes;