"use strict";

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

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

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

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

var _pickBy = _interopRequireDefault(require("lodash/pickBy"));

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

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

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

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

const RecordTypeInput = _cspaceInput.baseComponents.RecordTypeInput;
const contextTypes = {
  config: _propTypes.default.object
};

class ObjectNameInput extends _react.Component {
  constructor(props) {
    super(props);
    this.handleCommit = this.handleCommit.bind(this);
  }

  getRecordTypes() {
    const {
      config
    } = this.context;
    return (0, _pickBy.default)(config.recordTypes, recordTypeConfig => {
      const serviceType = (0, _get.default)(recordTypeConfig, ['serviceConfig', 'serviceType']);
      return serviceType === 'procedure' || serviceType === 'object' || serviceType === 'authority';
    });
  }

  handleCommit(path, recordType) {
    const {
      onCommit
    } = this.props;

    if (onCommit) {
      const {
        config
      } = this.context;
      const objectName = (0, _get.default)(config, ['recordTypes', recordType, 'serviceConfig', 'objectName']);
      onCommit(path, objectName || recordType);
    }
  }

  render() {
    const {
      value: objectName
    } = this.props;
    const {
      config
    } = this.context;
    let recordType = objectName && (0, _configHelpers.getRecordTypeNameByServiceObjectName)(config, objectName);

    if (typeof recordType === 'undefined') {
      recordType = null;
    }

    return _react.default.createElement(RecordTypeInput, _extends({}, this.props, {
      recordTypes: this.getRecordTypes(),
      value: recordType,
      onCommit: this.handleCommit
    }));
  }

}

exports.default = ObjectNameInput;
ObjectNameInput.propTypes = RecordTypeInput.propTypes;
ObjectNameInput.contextTypes = contextTypes;