'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 _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var MiniButton = _cspaceInput.baseComponents.MiniButton;


var messages = (0, _reactIntl.defineMessages)({
  search: {
    'id': 'searchPanel.search',
    'defaultMessage': 'Search'
  },
  titleWithCount: {
    'id': 'searchPanel.titleWithCount',
    'defaultMessage': '{title}: {totalItems, number}'
  },
  titleWithCountFiltered: {
    'id': 'searchPanel.titleWithCountFiltered',
    'defaultMessage': '{title}: {totalItems, number} (filtered)'
  }
});

var 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,
  recordType: _propTypes2.default.string,
  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
};

var defaultProps = {
  columnSetName: 'default',
  listType: 'common',
  showSearchButton: true
};

var contextTypes = {
  router: _propTypes2.default.object
};

var SearchPanel = function (_Component) {
  _inherits(SearchPanel, _Component);

  function SearchPanel() {
    _classCallCheck(this, SearchPanel);

    var _this = _possibleConstructorReturn(this, (SearchPanel.__proto__ || Object.getPrototypeOf(SearchPanel)).call(this));

    _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
    };
    return _this;
  }

  _createClass(SearchPanel, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.search();

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


      if (onSearchDescriptorChange) {
        onSearchDescriptorChange(searchDescriptor);
      }
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var prevSearchDescriptor = prevProps.searchDescriptor;
      var _props2 = this.props,
          searchDescriptor = _props2.searchDescriptor,
          onSearchDescriptorChange = _props2.onSearchDescriptorChange;


      if (!_immutable2.default.is(prevSearchDescriptor, searchDescriptor)) {
        this.search();

        if (onSearchDescriptorChange) {
          onSearchDescriptorChange(searchDescriptor);
        }
      }
    }
  }, {
    key: 'getSearchLocation',
    value: function getSearchLocation() {
      var searchDescriptor = this.props.searchDescriptor;


      var 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')));
    }
  }, {
    key: 'closeModal',
    value: function closeModal() {
      this.setState({
        isSearchToRelateModalOpen: false
      });
    }
  }, {
    key: 'handleAddButtonClick',
    value: function handleAddButtonClick() {
      this.setState({
        isSearchToRelateModalOpen: true
      });
    }
  }, {
    key: 'handleModalCancelButtonClick',
    value: function handleModalCancelButtonClick() {
      this.closeModal();
    }
  }, {
    key: 'handleModalCloseButtonClick',
    value: function handleModalCloseButtonClick() {
      this.closeModal();
    }
  }, {
    key: 'handlePageChange',
    value: function handlePageChange(pageNum) {
      var _props3 = this.props,
          onSearchDescriptorChange = _props3.onSearchDescriptorChange,
          searchDescriptor = _props3.searchDescriptor;


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

        onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('p', pageNum)));
      }
    }
  }, {
    key: 'handlePageSizeChange',
    value: function handlePageSizeChange(pageSize) {
      var _props4 = this.props,
          name = _props4.name,
          recordType = _props4.recordType,
          searchDescriptor = _props4.searchDescriptor,
          setPreferredPageSize = _props4.setPreferredPageSize,
          onSearchDescriptorChange = _props4.onSearchDescriptorChange;


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

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

        onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('p', 0).set('size', pageSize)));
      }
    }
  }, {
    key: 'handleRelationsCreated',
    value: function handleRelationsCreated() {
      this.closeModal();
    }
  }, {
    key: 'handleSortChange',
    value: function handleSortChange(sort) {
      var _props5 = this.props,
          onSearchDescriptorChange = _props5.onSearchDescriptorChange,
          searchDescriptor = _props5.searchDescriptor;


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

        onSearchDescriptorChange(searchDescriptor.set('searchQuery', searchQuery.set('sort', sort)));
      }
    }
  }, {
    key: 'search',
    value: function search() {
      var _props6 = this.props,
          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);
      }
    }
  }, {
    key: 'renderButtons',
    value: function renderButtons() {
      var _props7 = this.props,
          showAddButton = _props7.showAddButton,
          showSearchButton = _props7.showSearchButton;


      var 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;
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var _props8 = this.props,
          config = _props8.config,
          isFiltered = _props8.isFiltered,
          listType = _props8.listType,
          searchResult = _props8.searchResult,
          title = _props8.title;


      var listTypeConfig = config.listTypes[listType];

      var totalItems = searchResult ? searchResult.getIn([listTypeConfig.listNodeName, 'totalItems']) : null;

      var headerContent = void 0;

      if (typeof totalItems !== 'undefined' && totalItems !== null) {
        var messageKey = isFiltered ? 'titleWithCountFiltered' : 'titleWithCount';

        headerContent = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages[messageKey], {
          values: {
            title: title,
            totalItems: totalItems
          }
        }));
      } else {
        headerContent = title;
      }

      return _react2.default.createElement(
        'h3',
        null,
        headerContent
      );
    }
  }, {
    key: 'renderFooter',
    value: function renderFooter(_ref) {
      var searchResult = _ref.searchResult;
      var _props9 = this.props,
          config = _props9.config,
          listType = _props9.listType;


      if (searchResult) {
        var listTypeConfig = config.listTypes[listType];
        var list = searchResult.get(listTypeConfig.listNodeName);

        var totalItems = parseInt(list.get('totalItems'), 10);
        var pageSize = parseInt(list.get('pageSize'), 10);
        var pageNum = parseInt(list.get('pageNum'), 10);
        var 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: 'searchPanelPageSizes',
            windowSize: 3,
            onPageChange: this.handlePageChange,
            onPageSizeChange: this.handlePageSizeChange
          })
        );
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props10 = this.props,
          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,
          searchDescriptor = _props10.searchDescriptor,
          showAddButton = _props10.showAddButton,
          showCheckboxColumn = _props10.showCheckboxColumn,
          renderCheckbox = _props10.renderCheckbox,
          renderTableHeader = _props10.renderTableHeader,
          getItemLocation = _props10.getItemLocation,
          onItemClick = _props10.onItemClick;
      var isSearchToRelateModalOpen = this.state.isSearchToRelateModalOpen;


      var searchToRelateModal = void 0;

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

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

        var allowedServiceTypes = void 0;

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

        searchToRelateModal = _react2.default.createElement(_SearchToRelateModalContainer2.default, {
          allowedServiceTypes: allowedServiceTypes,
          subjects: [{ csid: searchDescriptor.getIn(['searchQuery', 'rel']), recordType: recordType }],
          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
      );
    }
  }]);

  return SearchPanel;
}(_react.Component);

exports.default = SearchPanel;


SearchPanel.propTypes = propTypes;
SearchPanel.defaultProps = defaultProps;
SearchPanel.contextTypes = contextTypes;