'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _reactRouterDom = require('react-router-dom');

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

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

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

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

var _SearchResultTableContainer2 = _interopRequireDefault(_SearchResultTableContainer);

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

var _SearchToRelateModalContainer2 = _interopRequireDefault(_SearchToRelateModalContainer);

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

var _Pager = require('./Pager');

var _Pager2 = _interopRequireDefault(_Pager);

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

var _SearchPanel2 = _interopRequireDefault(_SearchPanel);

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

const MiniButton = _cspaceInput.baseComponents.MiniButton;


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: _propTypes2.default.bool,
  color: _propTypes2.default.string,
  columnSetName: _propTypes2.default.string,
  config: _propTypes2.default.object,
  history: _propTypes2.default.object,
  isFiltered: _propTypes2.default.bool,
  linkItems: _propTypes2.default.bool,
  name: _propTypes2.default.string,
  pageSizeOptionListName: _propTypes2.default.string,
  recordType: _propTypes2.default.string,
  recordData: _propTypes2.default.instanceOf(_immutable2.default.Map),
  searchDescriptor: _propTypes2.default.instanceOf(_immutable2.default.Map),
  searchResult: _propTypes2.default.instanceOf(_immutable2.default.Map),
  listType: _propTypes2.default.string,
  title: _propTypes2.default.node,
  showAddButton: _propTypes2.default.bool,
  showSearchButton: _propTypes2.default.bool,
  showCheckboxColumn: _propTypes2.default.bool,
  renderCheckbox: _propTypes2.default.func,
  renderTableHeader: _propTypes2.default.func,
  search: _propTypes2.default.func,
  setPreferredPageSize: _propTypes2.default.func,
  getItemLocation: _propTypes2.default.func,
  onItemClick: _propTypes2.default.func,
  onSearchDescriptorChange: _propTypes2.default.func
};

const defaultProps = {
  columnSetName: 'default',
  listType: 'common',
  pageSizeOptionListName: 'searchPanelPageSizes',
  showSearchButton: true
};

const contextTypes = {
  intl: _reactIntl.intlShape,
  router: _propTypes2.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();

    var _props = this.props;
    const searchDescriptor = _props.searchDescriptor,
          onSearchDescriptorChange = _props.onSearchDescriptorChange;


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

  componentDidUpdate(prevProps) {
    const prevSearchDescriptor = prevProps.searchDescriptor,
          prevSearchResult = prevProps.searchResult;
    var _props2 = this.props;
    const searchDescriptor = _props2.searchDescriptor,
          searchResult = _props2.searchResult,
          onSearchDescriptorChange = _props2.onSearchDescriptorChange;


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

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

  getSearchLocation() {
    const searchDescriptor = this.props.searchDescriptor;


    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) {
    var _props3 = this.props;
    const onSearchDescriptorChange = _props3.onSearchDescriptorChange,
          searchDescriptor = _props3.searchDescriptor;


    if (onSearchDescriptorChange) {
      const searchQuery = searchDescriptor.get('searchQuery');

      onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('p', pageNum)));
    }
  }

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


    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) {
    var _props5 = this.props;
    const onSearchDescriptorChange = _props5.onSearchDescriptorChange,
          searchDescriptor = _props5.searchDescriptor;


    if (onSearchDescriptorChange) {
      const searchQuery = searchDescriptor.get('searchQuery');

      onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('sort', sort)));
    }
  }

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


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

  renderButtons() {
    var _props7 = this.props;
    const showAddButton = _props7.showAddButton,
          showSearchButton = _props7.showSearchButton;


    const buttons = [];

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

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

    return buttons;
  }

  renderHeader() {
    var _props8 = this.props;
    const config = _props8.config,
          isFiltered = _props8.isFiltered,
          listType = _props8.listType,
          searchResult = _props8.searchResult,
          title = _props8.title;


    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 = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages[messageKey], {
        values: {
          title,
          totalItems
        }
      }));
    } else {
      headerContent = title;
    }

    return _react2.default.createElement(
      'h3',
      null,
      headerContent
    );
  }

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


    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 _react2.default.createElement(
        'footer',
        null,
        _react2.default.createElement(_Pager2.default, {
          currentPage: pageNum,
          lastPage: lastPage,
          pageSize: pageSize,
          pageSizeOptionListName: pageSizeOptionListName,
          windowSize: 3,
          onPageChange: this.handlePageChange,
          onPageSizeChange: this.handlePageSizeChange
        })
      );
    }

    return null;
  }

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


    let searchToRelateModal;

    if (showAddButton) {
      const defaultRecordTypeValue = searchDescriptor.get('recordType');

      const defaultServiceType = (0, _get2.default)(config, ['recordTypes', defaultRecordTypeValue, 'serviceConfig', 'serviceType']);

      let allowedServiceTypes;

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

      const titleGetter = (0, _get2.default)(config, ['recordTypes', recordType, 'title']);
      const title = titleGetter && titleGetter(recordData, { config, intl });

      searchToRelateModal = _react2.default.createElement(_SearchToRelateModalContainer2.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 _react2.default.createElement(
      'div',
      null,
      _react2.default.createElement(
        _PanelContainer.ConnectedPanel,
        {
          buttons: this.renderButtons(),
          className: _SearchPanel2.default.common,
          collapsible: true,
          collapsed: collapsed,
          color: color,
          config: config,
          header: this.renderHeader(),
          name: name,
          recordType: recordType
        },
        _react2.default.createElement(_SearchResultTableContainer2.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;