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

var _immutable2 = _interopRequireDefault(_immutable);

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

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 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 isSortable is
 * true, and the search is not contrained 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 isSortable.
 */
var isSortable = function isSortable(column, searchDescriptor) {
  var sortBy = column.sortBy;


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

var propTypes = {
  columnSetName: _react.PropTypes.string,
  config: _react.PropTypes.object.isRequired,
  formatCellData: _react.PropTypes.func,
  formatColumnLabel: _react.PropTypes.func,
  isSearchPending: _react.PropTypes.bool,
  listType: _react.PropTypes.string,
  searchDescriptor: _react.PropTypes.object,
  searchError: _react.PropTypes.instanceOf(_immutable2.default.Map),
  searchResult: _react.PropTypes.instanceOf(_immutable2.default.Map),
  renderHeader: _react.PropTypes.func,
  renderFooter: _react.PropTypes.func,
  onSortChange: _react.PropTypes.func
};

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

var contextTypes = {
  router: _react.PropTypes.object
};

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

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

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

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

  _createClass(SearchResultTable, [{
    key: 'handleRowClick',
    value: function handleRowClick(index) {
      var _props = this.props,
          config = _props.config,
          listType = _props.listType,
          searchDescriptor = _props.searchDescriptor,
          searchResult = _props.searchResult;
      var router = this.context.router;


      if (searchResult && router) {
        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;

        var itemContext = { config: config, searchDescriptor: searchDescriptor };
        var itemLocation = listTypeConfig.getItemLocation(item, itemContext);

        if (itemLocation) {
          router.push(itemLocation);
        }
      }
    }
  }, {
    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.SORT_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: 'renderTable',
    value: function renderTable() {
      var _props2 = this.props,
          columnSetName = _props2.columnSetName,
          config = _props2.config,
          formatCellData = _props2.formatCellData,
          formatColumnLabel = _props2.formatColumnLabel,
          listType = _props2.listType,
          searchDescriptor = _props2.searchDescriptor,
          searchResult = _props2.searchResult;


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


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


        var sortColumnName = null;
        var sortDir = null;

        var sortSpec = searchQuery.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 = columnConfig.map(function (column) {
          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),
            label: formatColumnLabel(column),
            dataKey: column.dataKey || column.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);
            },
            onRowClick: this.handleRowClick,
            sort: this.sort,
            sortBy: sortColumnName,
            sortDirection: sortDir === 'desc' ? _cspaceLayout.Table.SORT_DESC : _cspaceLayout.Table.SORT_ASC,
            noRowsRenderer: this.renderNoItems
          })
        );
      }

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


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

  return SearchResultTable;
}(_react.Component);

exports.default = SearchResultTable;


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