"use strict";

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

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

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

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

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

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

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

var _cspaceLayout = require("cspace-layout");

var _InvokeButton = _interopRequireDefault(require("./InvokeButton"));

var _InvocationEditorContainer = _interopRequireDefault(require("../../containers/invocable/InvocationEditorContainer"));

var _invocationHelpers = require("../../helpers/invocationHelpers");

var _CancelButton = _interopRequireDefault(require("../navigation/CancelButton"));

var _InvocationModal = _interopRequireDefault(require("../../../styles/cspace-ui/InvocationModal.css"));

var _InvocationFormatPicker = _interopRequireDefault(require("../../../styles/cspace-ui/InvocationFormatPicker.css"));

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

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

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

const {
  Label
} = _cspaceInput.components;
const messages = (0, _reactIntl.defineMessages)({
  cancel: {
    "id": "invocationModal.cancel",
    "defaultMessage": "Cancel"
  },
  invoke: {
    "id": "invocationModal.run",
    "defaultMessage": "Run"
  },
  running: {
    "id": "invocationModal.running",
    "defaultMessage": "Running\u2026"
  },
  format: {
    "id": "invocationModal.format",
    "defaultMessage": "Format:"
  }
});
const propTypes = {
  allowedModes: _propTypes.default.arrayOf(_propTypes.default.string),
  config: _propTypes.default.shape({
    recordTypes: _propTypes.default.object
  }).isRequired,
  csid: _propTypes.default.string,
  data: _propTypes.default.instanceOf(_immutable.default.Map),
  initialInvocationDescriptor: _propTypes.default.instanceOf(_immutable.default.Map),
  modeReadOnly: _propTypes.default.bool,
  invocationTargetReadOnly: _propTypes.default.bool,
  isOpen: _propTypes.default.bool,
  isRecordModified: _propTypes.default.bool,
  isRunning: _propTypes.default.bool,
  recordType: _propTypes.default.oneOf(['report', 'batch']),
  readRecord: _propTypes.default.func,
  searchCsid: _propTypes.default.func,
  onCancelButtonClick: _propTypes.default.func,
  onCloseButtonClick: _propTypes.default.func,
  onInvokeButtonClick: _propTypes.default.func
};

class InvocationModal extends _react.Component {
  constructor(props) {
    super(props);
    this.handleFormatPickerCommit = this.handleFormatPickerCommit.bind(this);
    this.handleInvocationDescriptorCommit = this.handleInvocationDescriptorCommit.bind(this);
    this.handleInvokeButtonClick = this.handleInvokeButtonClick.bind(this);
    this.renderButtonBar = this.renderButtonBar.bind(this);
    const {
      data,
      initialInvocationDescriptor
    } = this.props;
    this.state = {
      invocationDescriptor: (0, _invocationHelpers.normalizeInvocationDescriptor)(initialInvocationDescriptor, data)
    };
  } // eslint-disable-next-line camelcase


  UNSAFE_componentWillReceiveProps(nextProps) {
    const {
      data,
      isOpen
    } = this.props;
    const {
      data: nextData,
      isOpen: nextIsOpen
    } = nextProps;

    if (!isOpen && nextIsOpen) {
      const {
        initialInvocationDescriptor
      } = nextProps;
      this.setState({
        invocationDescriptor: (0, _invocationHelpers.normalizeInvocationDescriptor)(initialInvocationDescriptor, nextData)
      });
    } else if (!data && nextData) {
      const {
        invocationDescriptor
      } = this.state;
      this.setState({
        invocationDescriptor: (0, _invocationHelpers.normalizeInvocationDescriptor)(invocationDescriptor, nextData)
      });
    }
  }

  componentDidUpdate(prevProps) {
    const {
      csid,
      isOpen,
      readRecord
    } = this.props;
    const {
      isOpen: prevIsOpen
    } = prevProps;

    if (csid && !prevIsOpen && isOpen) {
      if (readRecord) {
        readRecord();
      }

      this.readInvocationItem();
    }
  }

  handleFormatPickerCommit(path, value) {
    const {
      invocationDescriptor
    } = this.state;
    this.setState({
      invocationDescriptor: invocationDescriptor.set('outputMIME', value)
    });
  }

  handleInvocationDescriptorCommit(invocationDescriptor) {
    this.setState({
      invocationDescriptor
    });
  }

  handleInvokeButtonClick() {
    const {
      data,
      onInvokeButtonClick
    } = this.props;
    const {
      invocationDescriptor
    } = this.state;
    const mode = invocationDescriptor.get('mode'); // Translate the items map to csids.

    const items = invocationDescriptor.get('items') || _immutable.default.Map();

    let csid = items.keySeq().toJS();

    if (mode === 'single' || mode === 'group') {
      [csid] = csid;
    }

    if (onInvokeButtonClick) {
      onInvokeButtonClick(data, invocationDescriptor.set('csid', csid));
    }
  }

  readInvocationItem() {
    const {
      config,
      searchCsid
    } = this.props;
    const {
      invocationDescriptor
    } = this.state;

    if (invocationDescriptor) {
      const invocationCsid = invocationDescriptor.get('csid');

      if (invocationCsid && typeof invocationCsid === 'string' && !invocationDescriptor.get('items')) {
        searchCsid(config, invocationDescriptor.get('recordType'), invocationCsid).then(response => {
          let item = (0, _get.default)(response, ['data', 'ns2:abstract-common-list', 'list-item']);

          if (item) {
            item = _immutable.default.fromJS(item);
          } else {
            item = _immutable.default.Map({
              csid: invocationCsid
            });
          }

          this.setState(prevState => ({
            invocationDescriptor: prevState.invocationDescriptor.set('items', _immutable.default.Map({
              [invocationCsid]: item
            }))
          }));
        }).catch(() => {
          const item = _immutable.default.Map({
            csid: invocationCsid
          });

          this.setState(prevState => ({
            invocationDescriptor: prevState.invocationDescriptor.set('items', _immutable.default.Map({
              [invocationCsid]: item
            }))
          }));
        });
      }
    }
  }

  renderFormatPicker() {
    const {
      recordType,
      data
    } = this.props;
    const {
      invocationDescriptor
    } = this.state;

    if (recordType === 'report') {
      let mimeList = [];

      if (data) {
        mimeList = data.getIn(['document', 'ns2:reports_common', 'supportsOutputMIMEList', 'outputMIME']);
      }

      const prefilter = option => mimeList.includes(option.value);

      return /*#__PURE__*/_react.default.createElement("div", {
        className: _InvocationFormatPicker.default.common
      }, /*#__PURE__*/_react.default.createElement(_configContextInputs.OptionPickerInput, {
        blankable: false,
        label: /*#__PURE__*/_react.default.createElement(Label, null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.format)),
        source: "reportMimeTypes",
        prefilter: mimeList ? prefilter : null,
        value: invocationDescriptor.get('outputMIME'),
        onCommit: this.handleFormatPickerCommit // blankable

      }));
    }

    return null;
  }

  renderButtonBar() {
    const {
      isRunning,
      onCancelButtonClick,
      recordType
    } = this.props;
    const {
      invocationDescriptor
    } = this.state;
    const mode = invocationDescriptor.get('mode');
    const items = invocationDescriptor.get('items');
    return /*#__PURE__*/_react.default.createElement("div", null, this.renderFormatPicker(), /*#__PURE__*/_react.default.createElement(_CancelButton.default, {
      disabled: isRunning,
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.cancel),
      onClick: onCancelButtonClick
    }), /*#__PURE__*/_react.default.createElement(_InvokeButton.default, {
      disabled: isRunning || mode !== 'nocontext' && (!items || items.isEmpty()),
      label: /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.invoke),
      recordType: recordType,
      onClick: this.handleInvokeButtonClick
    }));
  }

  renderTitle() {
    const {
      config,
      data,
      recordType
    } = this.props;

    if (!data) {
      return ' ';
    }

    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
    const titleGetter = (0, _get.default)(recordTypeConfig, 'title');
    let title = titleGetter && titleGetter(data);

    if (!title) {
      const recordTypeMessages = (0, _get.default)(recordTypeConfig, ['messages', 'record']);
      title = /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, recordTypeMessages.name);
    }

    return /*#__PURE__*/_react.default.createElement("h1", null, title);
  }

  renderInvocationEditor() {
    const {
      allowedModes,
      config,
      data,
      modeReadOnly,
      invocationTargetReadOnly,
      isRecordModified,
      recordType
    } = this.props;
    const {
      invocationDescriptor
    } = this.state;
    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);
    const invocableNameGetter = (0, _get.default)(recordTypeConfig, 'invocableName');
    const invocableName = invocableNameGetter && invocableNameGetter(data);
    return /*#__PURE__*/_react.default.createElement(_InvocationEditorContainer.default, {
      allowedModes: allowedModes,
      config: config,
      metadata: data,
      invocationDescriptor: invocationDescriptor,
      modeReadOnly: modeReadOnly,
      invocationTargetReadOnly: invocationTargetReadOnly,
      invocableName: invocableName,
      isInvocationTargetModified: isRecordModified,
      recordType: recordType,
      onInvocationDescriptorCommit: this.handleInvocationDescriptorCommit
    });
  }

  render() {
    const {
      csid,
      isOpen,
      isRunning,
      onCloseButtonClick
    } = this.props;

    if (!isOpen || !csid) {
      return null;
    }

    let content;

    if (isRunning) {
      content = /*#__PURE__*/_react.default.createElement("p", null, /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, messages.running));
    } else {
      content = this.renderInvocationEditor();
    }

    return /*#__PURE__*/_react.default.createElement(_cspaceLayout.Modal, {
      className: isRunning ? _InvocationModal.default.running : _InvocationModal.default.common,
      isOpen: isOpen,
      title: this.renderTitle(),
      closeButtonClassName: "material-icons",
      closeButtonDisabled: isRunning,
      closeButtonLabel: "close",
      renderButtonBar: this.renderButtonBar,
      onCloseButtonClick: onCloseButtonClick
    }, content);
  }

}

exports.default = InvocationModal;
InvocationModal.propTypes = propTypes;