"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 _reactRouterDom = require("react-router-dom");

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

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

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

var _PanelContainer = require("../../containers/layout/PanelContainer");

var _SearchResultTableContainer = _interopRequireDefault(require("../../containers/search/SearchResultTableContainer"));

var _SearchToRelateModalContainer = _interopRequireDefault(require("../../containers/search/SearchToRelateModalContainer"));

var _searchHelpers = require("../../helpers/searchHelpers");

var _Pager = _interopRequireDefault(require("./Pager"));

var _SearchPanel = _interopRequireDefault(require("../../../styles/cspace-ui/SearchPanel.css"));

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { 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; }

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 {
  MiniButton
} = _cspaceInput.baseComponents;
const messages = (0, _reactIntl.defineMessages)({
  search: {
    "id": "searchPanel.openSearch",
    "defaultMessage": "Open"
  },
  titleWithCount: {
    "id": "searchPanel.titleWithCount",
    "defaultMessage": "{title}: {totalItems, number}"
  },
  titleWithCountFiltered: {
    "id": "searchPanel.titleWithCountFiltered",
    "defaultMessage": "{title}: {totalItems, number} (filtered)"
  }
});
const propTypes = {
  collapsed: _propTypes.default.bool,
  collapsible: _propTypes.default.bool,
  color: _propTypes.default.string,
  columnSetName: _propTypes.default.string,
  config: _propTypes.default.object,
  history: _propTypes.default.object,
  isFiltered: _propTypes.default.bool,
  linkItems: _propTypes.default.bool,
  name: _propTypes.default.string,
  pageSizeOptionListName: _propTypes.default.string,
  recordType: _propTypes.default.string,
  recordData: _propTypes.default.instanceOf(_immutable.default.Map),
  searchDescriptor: _propTypes.default.instanceOf(_immutable.default.Map),
  searchError: _propTypes.default.instanceOf(_immutable.default.Map),
  searchResult: _propTypes.default.instanceOf(_immutable.default.Map),
  listType: _propTypes.default.string,
  title: _propTypes.default.node,
  showAddButton: _propTypes.default.bool,
  showSearchButton: _propTypes.default.bool,
  showCheckboxColumn: _propTypes.default.bool,
  renderCheckbox: _propTypes.default.func,
  renderTableHeader: _propTypes.default.func,
  search: _propTypes.default.func,
  setPreferredPageSize: _propTypes.default.func,
  getItemLocation: _propTypes.default.func,
  onItemClick: _propTypes.default.func,
  onSearchDescriptorChange: _propTypes.default.func
};
const defaultProps = {
  collapsible: true,
  columnSetName: 'default',
  listType: 'common',
  pageSizeOptionListName: 'searchPanelPageSizes',
  showSearchButton: true
};
const contextTypes = {
  intl: _reactIntl.intlShape,
  router: _propTypes.default.object
};

class SearchPanel extends _react.Component {
  constructor() {
    super();
    this.renderFooter = this.renderFooter.bind(this);
    this.handlePageChange = this.handlePageChange.bind(this);
    this.handlePageSizeChange = this.handlePageSizeChange.bind(this);
    this.handleAddButtonClick = this.handleAddButtonClick.bind(this);
    this.handleModalCancelButtonClick = this.handleModalCancelButtonClick.bind(this);
    this.handleModalCloseButtonClick = this.handleModalCloseButtonClick.bind(this);
    this.handleRelationsCreated = this.handleRelationsCreated.bind(this);
    this.handleSortChange = this.handleSortChange.bind(this);
    this.renderButtons = this.renderButtons.bind(this);
    this.state = {
      isSearchToRelateModalOpen: false
    };
  }

  componentDidMount() {
    this.search();
    const {
      searchDescriptor,
      onSearchDescriptorChange
    } = this.props;

    if (onSearchDescriptorChange) {
      onSearchDescriptorChange(searchDescriptor);
    }
  }

  componentDidUpdate(prevProps) {
    const {
      searchDescriptor: prevSearchDescriptor,
      searchResult: prevSearchResult
    } = prevProps;
    const {
      searchDescriptor,
      searchError,
      searchResult,
      onSearchDescriptorChange
    } = this.props;

    if (!_immutable.default.is(prevSearchDescriptor, searchDescriptor) || // If the search result was cleared from the store (not due to the search failing), redo the
    // search.
    typeof searchResult === 'undefined' && prevSearchResult && !searchError) {
      this.search();

      if (onSearchDescriptorChange) {
        onSearchDescriptorChange(searchDescriptor);
      }
    }
  }

  getSearchLocation() {
    const {
      searchDescriptor
    } = this.props;
    const searchQuery = searchDescriptor.get('searchQuery'); // Always go to the first page, since the page size may differ on the search result page.
    // Remove the size, so that the default/preferred setting for the search result page will
    // take effect.

    return (0, _searchHelpers.searchDescriptorToLocation)(searchDescriptor.set('searchQuery', searchQuery.set('p', 0).delete('size')));
  }

  closeModal() {
    this.setState({
      isSearchToRelateModalOpen: false
    });
  }

  handleAddButtonClick() {
    this.setState({
      isSearchToRelateModalOpen: true
    });
  }

  handleModalCancelButtonClick() {
    this.closeModal();
  }

  handleModalCloseButtonClick() {
    this.closeModal();
  }

  handlePageChange(pageNum) {
    const {
      onSearchDescriptorChange,
      searchDescriptor
    } = this.props;

    if (onSearchDescriptorChange) {
      const searchQuery = searchDescriptor.get('searchQuery');
      onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('p', pageNum)));
    }
  }

  handlePageSizeChange(pageSize) {
    const {
      name,
      recordType,
      searchDescriptor,
      setPreferredPageSize,
      onSearchDescriptorChange
    } = this.props;

    if (setPreferredPageSize) {
      setPreferredPageSize(recordType, name, pageSize);
    }

    if (onSearchDescriptorChange) {
      const searchQuery = searchDescriptor.get('searchQuery');
      onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('p', 0).set('size', pageSize)));
    }
  }

  handleRelationsCreated() {
    this.closeModal();
  }

  handleSortChange(sort) {
    const {
      onSearchDescriptorChange,
      searchDescriptor
    } = this.props;

    if (onSearchDescriptorChange) {
      const searchQuery = searchDescriptor.get('searchQuery');
      onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('sort', sort)));
    }
  }

  search() {
    const {
      columnSetName,
      config,
      listType,
      name,
      search,
      searchDescriptor
    } = this.props;

    if (search) {
      search(config, name, searchDescriptor, listType, columnSetName);
    }
  }

  renderButtons() {
    const {
      showAddButton,
      showSearchButton
    } = this.props;
    const buttons = [];

    if (showSearchButton) {
      buttons.push(_react.default.createElement(_reactRouterDom.Link, {
        to: this.getSearchLocation(),
        key: "search"
      }, _react.default.createElement(_reactIntl.FormattedMessage, messages.search)));
    }

    if (showAddButton) {
      buttons.push(_react.default.createElement(MiniButton, {
        autoWidth: true,
        key: "add",
        name: "add",
        onClick: this.handleAddButtonClick
      }, "Add\u2026"));
    }

    return buttons;
  }

  renderHeader() {
    const {
      config,
      isFiltered,
      listType,
      searchResult,
      title
    } = this.props;
    const listTypeConfig = config.listTypes[listType];
    const totalItems = searchResult ? searchResult.getIn([listTypeConfig.listNodeName, 'totalItems']) : null;
    let headerContent;

    if (typeof totalItems !== 'undefined' && totalItems !== null) {
      const messageKey = isFiltered ? 'titleWithCountFiltered' : 'titleWithCount';
      headerContent = _react.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages[messageKey], {
        values: {
          title,
          totalItems
        }
      }));
    } else {
      headerContent = title;
    }

    return _react.default.createElement("h3", null, headerContent);
  }

  renderFooter(_ref) {
    let {
      searchResult
    } = _ref;
    const {
      config,
      listType,
      pageSizeOptionListName
    } = this.props;

    if (searchResult) {
      const listTypeConfig = config.listTypes[listType];
      const list = searchResult.get(listTypeConfig.listNodeName);
      const totalItems = parseInt(list.get('totalItems'), 10);
      const pageSize = parseInt(list.get('pageSize'), 10);
      const pageNum = parseInt(list.get('pageNum'), 10);
      const lastPage = Math.max(0, isNaN(totalItems) ? 0 : Math.ceil(totalItems / pageSize) - 1);
      return _react.default.createElement("footer", null, _react.default.createElement(_Pager.default, {
        currentPage: pageNum,
        lastPage: lastPage,
        pageSize: pageSize,
        pageSizeOptionListName: pageSizeOptionListName,
        windowSize: 3,
        onPageChange: this.handlePageChange,
        onPageSizeChange: this.handlePageSizeChange
      }));
    }

    return null;
  }

  render() {
    const {
      collapsed,
      collapsible,
      color,
      columnSetName,
      config,
      history,
      linkItems,
      listType,
      name,
      recordType,
      recordData,
      searchDescriptor,
      showAddButton,
      showCheckboxColumn,
      renderCheckbox,
      renderTableHeader,
      getItemLocation,
      onItemClick
    } = this.props;
    const {
      intl
    } = this.context;
    const {
      isSearchToRelateModalOpen
    } = this.state;
    let searchToRelateModal;

    if (showAddButton) {
      const defaultRecordTypeValue = searchDescriptor.get('recordType');
      const defaultServiceType = (0, _get.default)(config, ['recordTypes', defaultRecordTypeValue, 'serviceConfig', 'serviceType']);
      let allowedServiceTypes;

      if (defaultServiceType === 'utility') {
        allowedServiceTypes = [defaultRecordTypeValue];
      }

      const titleGetter = (0, _get.default)(config, ['recordTypes', recordType, 'title']);
      const title = titleGetter && titleGetter(recordData, {
        config,
        intl
      });
      searchToRelateModal = _react.default.createElement(_SearchToRelateModalContainer.default, {
        allowedServiceTypes: allowedServiceTypes,
        subjects: [{
          recordType,
          title,
          csid: searchDescriptor.getIn(['searchQuery', 'rel'])
        }],
        config: config,
        isOpen: isSearchToRelateModalOpen,
        defaultRecordTypeValue: defaultRecordTypeValue,
        onCancelButtonClick: this.handleModalCancelButtonClick,
        onCloseButtonClick: this.handleModalCloseButtonClick,
        onRelationsCreated: this.handleRelationsCreated
      });
    }

    return _react.default.createElement("div", null, _react.default.createElement(_PanelContainer.ConnectedPanel, {
      buttons: this.renderButtons(),
      className: _SearchPanel.default.common,
      collapsible: collapsible,
      collapsed: collapsed,
      color: color,
      config: config,
      header: this.renderHeader(),
      name: name,
      recordType: recordType
    }, _react.default.createElement(_SearchResultTableContainer.default, {
      columnSetName: columnSetName,
      config: config,
      history: history,
      linkItems: linkItems,
      listType: listType,
      recordType: recordType,
      searchName: name,
      searchDescriptor: searchDescriptor,
      showCheckboxColumn: showCheckboxColumn,
      renderCheckbox: renderCheckbox,
      renderHeader: renderTableHeader,
      renderFooter: this.renderFooter,
      getItemLocation: getItemLocation,
      onItemClick: onItemClick,
      onSortChange: this.handleSortChange
    })), searchToRelateModal);
  }

}

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