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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _isEqual = require('lodash/isEqual');

var _isEqual2 = _interopRequireDefault(_isEqual);

var _merge = require('lodash/merge');

var _merge2 = _interopRequireDefault(_merge);

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

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

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

var _SearchResultTableContainer2 = _interopRequireDefault(_SearchResultTableContainer);

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)({
  titleWithCount: {
    'id': 'searchPanel.titleWithCount',
    'defaultMessage': '{title}: {totalItems, number}'
  }
});

var propTypes = {
  collapsed: _react.PropTypes.bool,
  color: _react.PropTypes.string,
  columnSetName: _react.PropTypes.string,
  config: _react.PropTypes.object,
  csid: _react.PropTypes.string,
  name: _react.PropTypes.string,
  recordType: _react.PropTypes.string,
  searchDescriptor: _react.PropTypes.object,
  searchResult: _react.PropTypes.instanceOf(_immutable2.default.Map),
  listType: _react.PropTypes.string,
  title: _react.PropTypes.node,
  search: _react.PropTypes.func,
  setPreferredPageSize: _react.PropTypes.func,
  onSearchDescriptorChange: _react.PropTypes.func
};

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

var contextTypes = {
  router: _react.PropTypes.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.handleSearchButtonClick = _this.handleSearchButtonClick.bind(_this);
    _this.handleSortChange = _this.handleSortChange.bind(_this);
    _this.renderButtons = _this.renderButtons.bind(_this);
    return _this;
  }

  _createClass(SearchPanel, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.search();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var prevSearchDescriptor = prevProps.searchDescriptor;
      var searchDescriptor = this.props.searchDescriptor;


      if (!(0, _isEqual2.default)(prevSearchDescriptor, searchDescriptor)) {
        this.search();
      }
    }
  }, {
    key: 'handlePageChange',
    value: function handlePageChange(pageNum) {
      var _props = this.props,
          onSearchDescriptorChange = _props.onSearchDescriptorChange,
          searchDescriptor = _props.searchDescriptor;


      if (onSearchDescriptorChange) {
        onSearchDescriptorChange((0, _merge2.default)({}, searchDescriptor, {
          searchQuery: {
            p: pageNum
          }
        }));
      }
    }
  }, {
    key: 'handlePageSizeChange',
    value: function handlePageSizeChange(pageSize) {
      var _props2 = this.props,
          name = _props2.name,
          recordType = _props2.recordType,
          searchDescriptor = _props2.searchDescriptor,
          setPreferredPageSize = _props2.setPreferredPageSize,
          onSearchDescriptorChange = _props2.onSearchDescriptorChange;


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

      if (onSearchDescriptorChange) {
        onSearchDescriptorChange((0, _merge2.default)({}, searchDescriptor, {
          searchQuery: {
            p: 0,
            size: pageSize
          }
        }));
      }
    }
  }, {
    key: 'handleSortChange',
    value: function handleSortChange(sort) {
      var _props3 = this.props,
          onSearchDescriptorChange = _props3.onSearchDescriptorChange,
          searchDescriptor = _props3.searchDescriptor;


      if (onSearchDescriptorChange) {
        onSearchDescriptorChange((0, _merge2.default)({}, searchDescriptor, {
          searchQuery: {
            sort: sort
          }
        }));
      }
    }
  }, {
    key: 'handleSearchButtonClick',
    value: function handleSearchButtonClick() {
      var router = this.context.router;


      if (router) {
        // Convert the search descriptor to a location.

        var _props$searchDescript = this.props.searchDescriptor,
            recordType = _props$searchDescript.recordType,
            vocabulary = _props$searchDescript.vocabulary,
            csid = _props$searchDescript.csid,
            subresource = _props$searchDescript.subresource,
            searchQuery = _props$searchDescript.searchQuery;


        var pathParts = ['/list', recordType, vocabulary, csid, subresource];
        var pathname = pathParts.filter(function (part) {
          return !!part;
        }).join('/');

        var query = Object.assign({}, searchQuery, {
          // Always go to the first page, since the page size may differ on the search result page.
          p: '1',
          // Remove the size, so that the default/preferred setting for the search result page will
          // take effect.
          size: undefined
        });

        router.push({
          pathname: pathname,
          query: query
        });
      }
    }
  }, {
    key: 'search',
    value: function search() {
      var _props4 = this.props,
          columnSetName = _props4.columnSetName,
          config = _props4.config,
          listType = _props4.listType,
          name = _props4.name,
          search = _props4.search,
          searchDescriptor = _props4.searchDescriptor;


      if (search) {
        search(config, name, searchDescriptor, listType, columnSetName);
      }
    }
  }, {
    key: 'renderButtons',
    value: function renderButtons() {
      var csid = this.props.csid;


      return [
      // <MiniButton key="add">+</MiniButton>,
      _react2.default.createElement(
        MiniButton,
        {
          className: 'material-icons',
          disabled: !csid,
          key: 'search',
          name: 'search',
          onClick: this.handleSearchButtonClick
        },
        'search'
      )];
    }
  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var _props5 = this.props,
          config = _props5.config,
          listType = _props5.listType,
          searchResult = _props5.searchResult,
          title = _props5.title;


      var listTypeConfig = config.listTypes[listType];

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

      var headerContent = typeof totalItems !== 'undefined' && totalItems !== null ? _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, messages.titleWithCount, { values: { title: title, totalItems: totalItems } })) : title;

      return _react2.default.createElement(
        'h3',
        null,
        headerContent
      );
    }
  }, {
    key: 'renderFooter',
    value: function renderFooter(_ref) {
      var searchResult = _ref.searchResult;
      var _props6 = this.props,
          config = _props6.config,
          listType = _props6.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 _props7 = this.props,
          collapsed = _props7.collapsed,
          color = _props7.color,
          columnSetName = _props7.columnSetName,
          config = _props7.config,
          listType = _props7.listType,
          name = _props7.name,
          recordType = _props7.recordType,
          searchDescriptor = _props7.searchDescriptor;


      return _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,
          listType: listType,
          recordType: recordType,
          searchName: name,
          searchDescriptor: searchDescriptor,
          renderFooter: this.renderFooter,
          onSortChange: this.handleSortChange
        })
      );
    }
  }]);

  return SearchPanel;
}(_react.Component);

exports.default = SearchPanel;


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