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

exports.default = SearchResultSummary;

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 _PageSizeChooser = require('./PageSizeChooser');

var _PageSizeChooser2 = _interopRequireDefault(_PageSizeChooser);

var _errorCodes = require('../../constants/errorCodes');

var _SearchResultSummary = require('../../../styles/cspace-ui/SearchResultSummary.css');

var _SearchResultSummary2 = _interopRequireDefault(_SearchResultSummary);

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

const messages = (0, _reactIntl.defineMessages)({
  error: {
    'id': 'searchResultSummary.error',
    'defaultMessage': 'Error: {code}'
  },
  [_errorCodes.ERR_NOT_ALLOWED]: {
    'id': 'searchResultSummary.ERR_NOT_ALLOWED',
    'defaultMessage': 'You\'re not allowed to perform this search.'
  },
  editSearch: {
    'id': 'searchResultSummary.editSearch',
    'defaultMessage': 'Revise search'
  }
});

const propTypes = {
  config: _propTypes2.default.object,
  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),
  renderEditLink: _propTypes2.default.func,
  onEditSearchLinkClick: _propTypes2.default.func,
  onPageSizeChange: _propTypes2.default.func
};

const defaultProps = {
  renderEditLink: (searchDescriptor, onEditSearchLinkClick) => {
    const recordType = searchDescriptor.get('recordType');
    const vocabulary = searchDescriptor.get('vocabulary');
    const subresource = searchDescriptor.get('subresource');
    const searchQuery = searchDescriptor.get('searchQuery');

    if (subresource || searchQuery.get('rel')) {
      // Services layer does not allow combining related record searches or subresource
      // (terms/refs) searches with keywords or advanced search conditions, so don't render an edit
      // search link.

      return null;
    }

    const vocabularyPath = vocabulary ? `/${vocabulary}` : '';
    const path = `/search/${recordType}${vocabularyPath}`;

    return _react2.default.createElement(
      _reactRouterDom.Link,
      { to: path, onClick: onEditSearchLinkClick },
      _react2.default.createElement(_reactIntl.FormattedMessage, messages.editSearch)
    );
  }
};

function SearchResultSummary(props) {
  const config = props.config,
        listType = props.listType,
        searchDescriptor = props.searchDescriptor,
        searchError = props.searchError,
        searchResult = props.searchResult,
        renderEditLink = props.renderEditLink,
        onEditSearchLinkClick = props.onEditSearchLinkClick,
        onPageSizeChange = props.onPageSizeChange;


  if (searchError) {
    const error = searchError.toJS();

    let code = error.code;


    if (code === _errorCodes.ERR_API) {
      const status = (0, _get2.default)(error, ['error', 'response', 'status']);

      if (status === 401) {
        // Convert 401 to ERR_NOT_ALLOWED.
        code = _errorCodes.ERR_NOT_ALLOWED;
      }
    }

    const message = messages[code] || messages.error;

    return _react2.default.createElement(
      'div',
      { className: _SearchResultSummary2.default.error },
      _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, message, { values: error })),
      _react2.default.createElement(
        'p',
        null,
        renderEditLink(searchDescriptor, onEditSearchLinkClick)
      )
    );
  }

  let message = null;
  let pageSize = null;

  if (searchResult) {
    const listTypeConfig = config.listTypes[listType];
    const listNodeName = listTypeConfig.listNodeName;


    const list = searchResult.get(listNodeName);
    const totalItems = parseInt(list.get('totalItems'), 10);

    if (isNaN(totalItems)) {
      message = _react2.default.createElement(_reactIntl.FormattedMessage, listTypeConfig.messages.searching);
    } else {
      const pageNum = parseInt(list.get('pageNum'), 10);

      pageSize = parseInt(list.get('pageSize'), 10);

      const startNum = pageNum * pageSize + 1;
      const endNum = Math.min(pageNum * pageSize + pageSize, totalItems);

      message = _react2.default.createElement(_reactIntl.FormattedMessage, _extends({}, listTypeConfig.messages.resultCount, {
        values: {
          totalItems,
          startNum,
          endNum
        }
      }));
    }
  }

  if (pageSize === null) {
    pageSize = searchDescriptor.getIn(['searchQuery', 'size']);
  }

  const editLink = renderEditLink(searchDescriptor, onEditSearchLinkClick);

  const content = _react2.default.createElement(
    'div',
    null,
    message,
    message && editLink ? ' | ' : '',
    editLink
  );

  const pageSizeChooser = _react2.default.createElement(_PageSizeChooser2.default, {
    pageSize: pageSize,
    onPageSizeChange: onPageSizeChange
  });

  return _react2.default.createElement(
    'div',
    { className: _SearchResultSummary2.default.normal },
    content,
    pageSizeChooser
  );
}

SearchResultSummary.propTypes = propTypes;
SearchResultSummary.defaultProps = defaultProps;