"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 _reactIntl = require("react-intl");

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

var _InvocationModal = _interopRequireDefault(require("../invocable/InvocationModal"));

var _InvocableSearchBar = _interopRequireDefault(require("../invocable/InvocableSearchBar"));

var _searchOperators = require("../../constants/searchOperators");

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

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

var _RecordEditorContainer = _interopRequireDefault(require("../../containers/record/RecordEditorContainer"));

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

var _AdminTab = _interopRequireDefault(require("../../../styles/cspace-ui/AdminTab.css"));

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

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 propTypes = {
  history: _propTypes.default.object,
  match: _propTypes.default.object,
  perms: _propTypes.default.instanceOf(_immutable.default.Map),
  filterDelay: _propTypes.default.number,
  openModalName: _propTypes.default.string,
  closeModal: _propTypes.default.func,
  openModal: _propTypes.default.func,
  invoke: _propTypes.default.func,
  setToolTab: _propTypes.default.func
};
const defaultProps = {
  filterDelay: 500
};
const contextTypes = {
  config: _propTypes.default.object.isRequired
};
const recordType = 'batch';

const getSearchDescriptor = () => _immutable.default.fromJS({
  recordType,
  searchQuery: {
    size: 20,
    sort: 'name'
  }
});

class BatchPage extends _react.Component {
  constructor() {
    super();
    this.handleSearchDescriptorChange = this.handleSearchDescriptorChange.bind(this);
    this.renderSearchBar = this.renderSearchBar.bind(this);
    this.handleSearchBarChange = this.handleSearchBarChange.bind(this);
    this.handleItemClick = this.handleItemClick.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.bind(this);
    this.handleModalInvokeButtonClick = this.handleModalInvokeButtonClick.bind(this);
    this.handleRunButtonClick = this.handleRunButtonClick.bind(this);
    this.state = {
      searchDescriptor: getSearchDescriptor()
    };
  }

  componentDidMount() {
    const {
      setToolTab
    } = this.props;

    if (setToolTab) {
      setToolTab(recordType);
    }
  }

  filter(value) {
    const {
      searchDescriptor
    } = this.state;
    const searchQuery = searchDescriptor.get('searchQuery');
    let updatedSearchQuery;

    if (value) {
      updatedSearchQuery = searchQuery.set('as', _immutable.default.fromJS({
        value,
        op: _searchOperators.OP_CONTAIN,
        path: 'ns2:batch_common/name'
      }));
    } else {
      updatedSearchQuery = searchQuery.delete('as');
    }

    updatedSearchQuery = updatedSearchQuery.set('p', 0);
    this.setState({
      filterValue: value,
      searchDescriptor: searchDescriptor.set('searchQuery', updatedSearchQuery)
    });
  }

  handleItemClick(item) {
    const {
      history,
      perms
    } = this.props;

    if ((0, _permissionHelpers.canRead)(recordType, perms)) {
      const csid = item.get('csid');
      history.replace("/tool/".concat(recordType, "/").concat(csid));
    }

    return false;
  }

  handleModalCancelButtonClick(event) {
    const {
      closeModal
    } = this.props;

    if (closeModal) {
      event.stopPropagation();
      closeModal();
    }
  }

  handleModalInvokeButtonClick(batchMetadata, invocationDescriptor) {
    // FIXME: Consolidate similar code in RecordBatchPanel and SearchResultBatchPanel.
    const {
      closeModal,
      history,
      invoke
    } = this.props;
    const {
      config
    } = this.context;

    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 {
          closeModal();
        }
      };

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

        if (createsNewFocus) {
          closeModal(); // 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);
          }
        }
      });
    }
  }

  handleRunButtonClick() {
    const {
      openModal
    } = this.props;

    if (openModal) {
      openModal(_InvocationModal.default.modalName);
    }
  }

  handleSearchBarChange(value) {
    if (this.filterTimer) {
      window.clearTimeout(this.filterTimer);
      this.filterTimer = null;
    }

    if (value) {
      const {
        filterDelay
      } = this.props;
      this.filterTimer = window.setTimeout(() => {
        this.filter(value);
        this.filterTimer = null;
      }, filterDelay);
    } else {
      this.filter(value);
    }
  }

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

  renderSearchBar() {
    const {
      filterValue
    } = this.state;
    return _react.default.createElement(_InvocableSearchBar.default, {
      value: filterValue,
      onChange: this.handleSearchBarChange
    });
  }

  renderInvocationModal() {
    const {
      match,
      openModalName
    } = this.props;
    const {
      isRunning
    } = this.state;
    const {
      config
    } = this.context;
    return _react.default.createElement(_InvocationModalContainer.default, {
      config: config,
      csid: match.params.csid,
      initialInvocationDescriptor: _immutable.default.Map({
        mode: 'nocontext'
      }),
      isOpen: openModalName === _InvocationModal.default.modalName,
      isRunning: isRunning,
      recordType: "batch",
      onCancelButtonClick: this.handleModalCancelButtonClick,
      onCloseButtonClick: this.handleModalCancelButtonClick,
      onInvokeButtonClick: this.handleModalInvokeButtonClick
    });
  }

  render() {
    const {
      config
    } = this.context;
    const {
      filterValue,
      searchDescriptor
    } = this.state;
    const {
      history,
      match,
      perms
    } = this.props;
    const {
      csid
    } = match.params;
    const normalizedCsid = csid === 'new' ? '' : csid;
    const recordTypeConfig = (0, _get.default)(config, ['recordTypes', recordType]);

    const title = _react.default.createElement(_reactIntl.FormattedMessage, recordTypeConfig.messages.record.collectionName);

    let recordEditor;

    if (typeof normalizedCsid !== 'undefined' && normalizedCsid !== null) {
      // Temporarily disallow deleting or creating records.
      let restrictedPerms = perms;
      restrictedPerms = (0, _permissionHelpers.disallowCreate)(recordType, restrictedPerms);
      restrictedPerms = (0, _permissionHelpers.disallowDelete)(recordType, restrictedPerms);
      restrictedPerms = (0, _permissionHelpers.disallowSoftDelete)(recordType, restrictedPerms);
      recordEditor = _react.default.createElement(_RecordEditorContainer.default, {
        config: config,
        csid: normalizedCsid,
        recordType: recordType,
        perms: restrictedPerms,
        onRunButtonClick: this.handleRunButtonClick
      });
    }

    return _react.default.createElement("div", {
      className: _AdminTab.default.common
    }, _react.default.createElement(_SearchPanelContainer.default, {
      collapsed: false,
      collapsible: false,
      config: config,
      history: history,
      isFiltered: !!filterValue,
      linkItems: false,
      name: "batchPage",
      searchDescriptor: searchDescriptor,
      title: title,
      recordType: recordType,
      showSearchButton: false,
      renderTableHeader: this.renderSearchBar,
      onItemClick: this.handleItemClick,
      onSearchDescriptorChange: this.handleSearchDescriptorChange
    }), recordEditor, this.renderInvocationModal());
  }

}

exports.default = BatchPage;
BatchPage.propTypes = propTypes;
BatchPage.defaultProps = defaultProps;
BatchPage.contextTypes = contextTypes;