'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

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 _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

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

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

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

var _get2 = _interopRequireDefault(_get);

var _cspaceLayout = require('cspace-layout');

var _SearchResultTable = require('../../../styles/cspace-ui/SearchResultTable.css');

var _SearchResultTable2 = _interopRequireDefault(_SearchResultTable);

var _SearchResultEmpty = require('../../../styles/cspace-ui/SearchResultEmpty.css');

var _SearchResultEmpty2 = _interopRequireDefault(_SearchResultEmpty);

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 rowHeight = 22;
var rowLinkStyle = {};

var messages = (0, _reactIntl.defineMessages)({
  searchPending: {
    'id': 'searchResultTable.searchPending',
    'defaultMessage': '\u22EF'
  }
});

/**
 * Determines if a column is sortable for a given search. A column is sortable if sortBy is truthy,
 * and the search is not constrained by a related record, or if it is, the field to sort by is not
 * complex. This is here to deal with CSPACE-5366 (searches with related record constraints are
 * done using CMIS, which can't see into complex fields). If that bug is ever fixed, then it will
 * suffice just to check sortBy.
 */
var isSortable = function isSortable(column, searchDescriptor) {
  var sortBy = column.sortBy;


  return sortBy && (!searchDescriptor.getIn(['searchQuery', 'rel']) || sortBy.indexOf('/0/') === -1);
};

var propTypes = {
  columnSetName: _propTypes2.default.string,
  config: _propTypes2.default.object.isRequired,
  formatCellData: _propTypes2.default.func,
  formatColumnLabel: _propTypes2.default.func,
  isSearchPending: _propTypes2.default.bool,
  linkItems: _propTypes2.default.bool,
  listType: _propTypes2.default.string,
  searchDescriptor: _propTypes2.default.instanceOf(_immutable2.default.Map),
  searchError: _propTypes2.default.instanceOf(_immutable2.default.Map),
  searchResult: _propTypes2.default.instanceOf(_immutable2.default.Map),
  showCheckboxColumn: _propTypes2.default.bool,
  renderCheckbox: _propTypes2.default.func,
  renderHeader: _propTypes2.default.func,
  renderFooter: _propTypes2.default.func,
  renderSelectBar: _propTypes2.default.func,
  getItemLocation: _propTypes2.default.func,
  onItemClick: _propTypes2.default.func,
  onSortChange: _propTypes2.default.func
};

var defaultProps = {
  columnSetName: 'default',
  formatCellData: function formatCellData(column, data) {
    return data;
  },
  formatColumnLabel: function formatColumnLabel(column) {
    return (0, _get2.default)(column, ['messages', 'label', 'defaultMessage']);
  },
  linkItems: true,
  listType: 'common',
  renderHeader: function renderHeader() {
    return null;
  },
  renderFooter: function renderFooter() {
    return null;
  },
  renderSelectBar: function renderSelectBar() {
    return null;
  }
};

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

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

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

    _this.getItemLocation = _this.getItemLocation.bind(_this);
    _this.handleRowClick = _this.handleRowClick.bind(_this);
    _this.renderNoItems = _this.renderNoItems.bind(_this);
    _this.renderRow = _this.renderRow.bind(_this);
    _this.sort = _this.sort.bind(_this);
    return _this;
  }

  _createClass(SearchResultTable, [{
    key: 'getItemLocation',
    value: function getItemLocation(item) {
      var _props = this.props,
          config = _props.config,
          listType = _props.listType,
          searchDescriptor = _props.searchDescriptor;


      var getItemLocationPath = (0, _get2.default)(config, ['listTypes', listType, 'getItemLocationPath']);

      if (!getItemLocationPath) {
        return undefined;
      }

      var itemContext = { config: config, searchDescriptor: searchDescriptor };
      var itemLocationPath = getItemLocationPath(item, itemContext);

      if (!itemLocationPath) {
        return undefined;
      }

      // Create a location with the item location path, along with enough state to reproduce this
      // search. The search descriptor is converted to an object in order to reliably store it in
      // location state.

      return {
        pathname: itemLocationPath,
        state: {
          searchDescriptor: searchDescriptor.toJS(),
          // The search traverser on records will always link to the search result page, so use
          // its search name.
          searchName: 'searchResultPage'
        }
      };
    }
  }, {
    key: 'handleRowClick',
    value: function handleRowClick(index) {
      var _props2 = this.props,
          config = _props2.config,
          listType = _props2.listType,
          searchResult = _props2.searchResult,
          onItemClick = _props2.onItemClick;


      if (onItemClick) {
        var listTypeConfig = config.listTypes[listType];
        var listNodeName = listTypeConfig.listNodeName,
            itemNodeName = listTypeConfig.itemNodeName;


        var items = searchResult.getIn([listNodeName, itemNodeName]);
        var item = _immutable2.default.List.isList(items) ? items.get(index) : items;

        onItemClick(item);
      }
    }
  }, {
    key: 'sort',
    value: function sort(_ref) {
      var sortBy = _ref.sortBy,
          sortDirection = _ref.sortDirection;
      var onSortChange = this.props.onSortChange;


      if (onSortChange) {
        onSortChange(sortBy + (sortDirection === _cspaceLayout.Table.SortDirection.DESC ? ' desc' : ''));
      }
    }
  }, {
    key: 'renderNoItems',
    value: function renderNoItems() {
      var isSearchPending = this.props.isSearchPending;


      var message = isSearchPending ? _react2.default.createElement(_reactIntl.FormattedMessage, messages.searchPending) : null;

      return _react2.default.createElement(
        'div',
        { className: _SearchResultEmpty2.default.common },
        message
      );
    }
  }, {
    key: 'renderRow',
    value: function renderRow(params) {
      var getItemLocation = this.props.getItemLocation;
      var key = params.key,
          rowData = params.rowData;


      var locationGetter = getItemLocation || this.getItemLocation;
      var location = locationGetter(rowData);

      if (!location) {
        return _cspaceLayout.Table.defaultRowRenderer(params);
      }

      var innerParams = Object.assign({}, params);

      delete innerParams.key;

      return _react2.default.createElement(
        _reactRouterDom.Link,
        { key: key, to: location, style: rowLinkStyle },
        _cspaceLayout.Table.defaultRowRenderer(innerParams)
      );
    }
  }, {
    key: 'renderTable',
    value: function renderTable() {
      var _props3 = this.props,
          columnSetName = _props3.columnSetName,
          config = _props3.config,
          formatCellData = _props3.formatCellData,
          formatColumnLabel = _props3.formatColumnLabel,
          linkItems = _props3.linkItems,
          listType = _props3.listType,
          searchDescriptor = _props3.searchDescriptor,
          searchResult = _props3.searchResult,
          showCheckboxColumn = _props3.showCheckboxColumn,
          renderCheckbox = _props3.renderCheckbox;


      if (searchResult) {
        var recordType = searchDescriptor.get('recordType');
        var subresource = searchDescriptor.get('subresource');
        var searchQuery = searchDescriptor.get('searchQuery');

        var listTypeConfig = config.listTypes[listType];
        var listNodeName = listTypeConfig.listNodeName,
            itemNodeName = listTypeConfig.itemNodeName;


        var sortColumnName = null;
        var sortDir = null;

        var sortSpec = searchQuery.get('sort');

        if (sortSpec) {
          var _sortSpec$split = sortSpec.split(' ');

          var _sortSpec$split2 = _slicedToArray(_sortSpec$split, 2);

          sortColumnName = _sortSpec$split2[0];
          sortDir = _sortSpec$split2[1];
        }

        var list = searchResult.get(listNodeName);
        var pageSize = parseInt(list.get('pageSize'), 10);
        var totalItems = parseInt(list.get('totalItems'), 10);
        var itemsInPage = parseInt(list.get('itemsInPage'), 10);

        var items = list.get(itemNodeName);

        if (!items) {
          items = _immutable2.default.List();
        }

        if (!_immutable2.default.List.isList(items)) {
          // If there's only one result, it won't be returned as a list.
          items = _immutable2.default.List.of(items);
        }

        var columnConfigurer = subresource ? config.subresources[subresource] : config.recordTypes[recordType];

        var columnConfig = (0, _get2.default)(columnConfigurer, ['columns', columnSetName]) || [];

        var columns = Object.keys(columnConfig).filter(function (name) {
          return !columnConfig[name].disabled;
        }).sort(function (nameA, nameB) {
          var orderA = columnConfig[nameA].order;
          var orderB = columnConfig[nameB].order;

          return orderA - orderB;
        }).map(function (name) {
          var column = columnConfig[name];

          return {
            cellDataGetter: function cellDataGetter(_ref2) {
              var dataKey = _ref2.dataKey,
                  rowData = _ref2.rowData;
              return formatCellData(column, rowData ? rowData.get(dataKey) : null, rowData);
            },
            disableSort: !isSortable(column, searchDescriptor),
            flexGrow: column.flexGrow,
            flexShrink: column.flexShrink,
            label: formatColumnLabel(column),
            dataKey: column.dataKey || name,
            width: column.width
          };
        });

        var heightBasis = void 0;

        if (isNaN(totalItems)) {
          // We don't yet know how many items are found by the search. Set the height to one item, so
          // an ellipsis (or other calculating indicator) can be shown.

          heightBasis = 1;
        } else {
          // If all of the search results fit on one page, shrink the table to fit the number of
          // results. Otherwise, size the table to fit the desired page size, even if there aren't
          // that many results on this page. This keeps the pager from jumping up on the last page
          // and while page/sorting changes are in progress.

          heightBasis = totalItems <= pageSize && !isNaN(itemsInPage) ? itemsInPage : pageSize;

          if (heightBasis === 0) {
            // If there are no items, set the height to one, because it looks weird when the footer
            // is mashed up against the header. This also leaves room to display a "no records found"
            // message if desired.

            heightBasis = 1;
          }
        }

        var height = heightBasis * rowHeight + rowHeight;

        return _react2.default.createElement(
          'div',
          { style: { height: height } },
          _react2.default.createElement(_cspaceLayout.Table, {
            columns: columns,
            rowCount: items.size,
            rowGetter: function rowGetter(_ref3) {
              var index = _ref3.index;
              return items.get(index);
            },
            showCheckboxColumn: showCheckboxColumn,
            onRowClick: this.handleRowClick,
            renderCheckbox: renderCheckbox,
            sort: this.sort,
            sortBy: sortColumnName,
            sortDirection: sortDir === 'desc' ? _cspaceLayout.Table.SortDirection.DESC : _cspaceLayout.Table.SortDirection.ASC,
            noRowsRenderer: this.renderNoItems,
            rowRenderer: linkItems ? this.renderRow : undefined
          })
        );
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props,
          isSearchPending = _props4.isSearchPending,
          searchError = _props4.searchError,
          searchResult = _props4.searchResult,
          renderHeader = _props4.renderHeader,
          renderSelectBar = _props4.renderSelectBar,
          renderFooter = _props4.renderFooter;


      return _react2.default.createElement(
        'div',
        { className: _SearchResultTable2.default.common },
        renderHeader({ isSearchPending: isSearchPending, searchError: searchError, searchResult: searchResult }),
        renderSelectBar(),
        this.renderTable(),
        renderFooter({ isSearchPending: isSearchPending, searchError: searchError, searchResult: searchResult })
      );
    }
  }]);

  return SearchResultTable;
}(_react.Component);

exports.default = SearchResultTable;


SearchResultTable.propTypes = propTypes;
SearchResultTable.defaultProps = defaultProps;