"use strict";

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

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

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

var _immutable = _interopRequireDefault(require("immutable"));

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

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

var _permissionHelpers = require("../../helpers/permissionHelpers");

var _recordDataHelpers = require("../../helpers/recordDataHelpers");

var _uriHelpers = require("../../helpers/uriHelpers");

var _InvocationModalContainer = _interopRequireDefault(require("../../containers/invocable/InvocationModalContainer"));

var _SearchPanelContainer = _interopRequireDefault(require("../../containers/search/SearchPanelContainer"));

var _searchNames = require("../../constants/searchNames");

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

/* global window */
const messages = (0, _reactIntl.defineMessages)({
  title: {
    "id": "recordBatchPanel.title",
    "defaultMessage": "Data Updates"
  }
});

const getSearchDescriptor = (config, recordType) => {
  const objectName = (0, _get.default)(config, ['recordTypes', recordType, 'serviceConfig', 'objectName']);
  return _immutable.default.fromJS({
    recordType: 'batch',
    searchQuery: {
      p: 0,
      size: 5,
      doctype: objectName,
      mode: recordType === 'group' ? ['single', 'group'] : 'single'
    }
  });
};

const propTypes = {
  color: _propTypes.default.string,
  config: _propTypes.default.object,
  csid: _propTypes.default.string,
  history: _propTypes.default.object,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  recordData: _propTypes.default.instanceOf(_immutable.default.Map),
  recordType: _propTypes.default.string,
  invoke: _propTypes.default.func
};

class RecordBatchPanel extends _react.Component {
  constructor(props) {
    super(props);
    this.handleItemClick = this.handleItemClick.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.bind(this);
    this.handleModalCloseButtonClick = this.handleModalCloseButtonClick.bind(this);
    this.handleModalInvokeButtonClick = this.handleModalInvokeButtonClick.bind(this);
    this.handleSearchDescriptorChange = this.handleSearchDescriptorChange.bind(this);
    const {
      config,
      recordType
    } = this.props;
    this.state = {
      searchDescriptor: getSearchDescriptor(config, recordType)
    };
  }

  componentWillReceiveProps(nextProps) {
    const {
      recordType
    } = this.props;
    const {
      config,
      recordType: nextRecordType
    } = nextProps;

    if (nextRecordType !== recordType) {
      this.setState({
        searchDescriptor: getSearchDescriptor(config, nextRecordType)
      });
    }
  }

  handleItemClick(item) {
    this.setState({
      isModalOpen: true,
      selectedItem: item
    });
  }

  handleModalCancelButtonClick() {
    this.setState({
      isModalOpen: false
    });
  }

  handleModalCloseButtonClick() {
    this.setState({
      isModalOpen: false
    });
  }

  handleModalInvokeButtonClick(batchMetadata, invocationDescriptor) {
    const {
      config,
      history,
      invoke
    } = this.props;

    if (invoke) {
      const createsNewFocus = batchMetadata.getIn(['document', 'ns2:batch_common', 'createsNewFocus']) === 'true';

      const handleValidationSuccess = () => {
        if (createsNewFocus) {
          // If the batch job is going to direct us to a different record, keep the modal in place
          // until it completes, so the user won't be surprised by a new record opening.
          this.setState({
            isRunning: true
          });
        } else {
          this.setState({
            isModalOpen: false
          });
        }
      };

      this.setState({
        isRunning: true
      });
      invoke(config, batchMetadata, invocationDescriptor, handleValidationSuccess).then(response => {
        this.setState({
          isModalOpen: false,
          isRunning: false
        });

        if (createsNewFocus) {
          // Open the record indicated by the invocation result.
          const uri = (0, _get.default)(response.data, ['ns2:invocationResults', 'primaryURICreated']);
          const location = (0, _uriHelpers.serviceUriToLocation)(config, uri);

          if (location) {
            history.push(location);
          }
        }
      });
    }
  }

  handleSearchDescriptorChange(searchDescriptor) {
    this.setState({
      searchDescriptor
    });
  }

  render() {
    const {
      color,
      config,
      csid,
      perms,
      recordData,
      recordType
    } = this.props;
    const {
      isModalOpen,
      isRunning,
      searchDescriptor,
      selectedItem
    } = this.state;

    if (!(0, _recordDataHelpers.isExistingRecord)(recordData)) {
      // Don't render until after the record has loaded.
      return null;
    }

    if (!(0, _permissionHelpers.canList)('batch', perms)) {
      return null;
    }

    const canRun = (0, _permissionHelpers.canCreate)('batch', perms);
    return _react.default.createElement("div", null, _react.default.createElement(_SearchPanelContainer.default, {
      collapsed: true,
      color: color,
      config: config,
      linkItems: false,
      name: _searchNames.RECORD_BATCH_PANEL_SEARCH_NAME,
      searchDescriptor: searchDescriptor,
      recordType: recordType,
      showSearchButton: false,
      title: _react.default.createElement(_reactIntl.FormattedMessage, messages.title),
      onItemClick: canRun ? this.handleItemClick : undefined,
      onSearchDescriptorChange: this.handleSearchDescriptorChange
    }), _react.default.createElement(_InvocationModalContainer.default, {
      allowedModes: recordType === 'group' ? ['group', 'single'] : undefined,
      config: config,
      csid: selectedItem && selectedItem.get('csid'),
      initialInvocationDescriptor: _immutable.default.Map({
        csid,
        recordType,
        mode: recordType === 'group' ? 'group' : 'single'
      }),
      modeReadOnly: recordType !== 'group',
      invocationTargetReadOnly: true,
      isOpen: isModalOpen,
      isRunning: isRunning,
      recordType: "batch",
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCloseButtonClick,
      onInvokeButtonClick: this.handleModalInvokeButtonClick
    }));
  }

}

exports.default = RecordBatchPanel;
RecordBatchPanel.propTypes = propTypes;