'use strict';

exports.__esModule = true;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactInstantsearchDom = require('react-instantsearch-dom');

var _Pagination = require('../Pagination');

var _Pagination2 = _interopRequireDefault(_Pagination);

var _Title = require('../../../../components/Title');

var _Title2 = _interopRequireDefault(_Title);

var _styleModule = require('./style.module.scss');

var _styleModule2 = _interopRequireDefault(_styleModule);

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

// custom results
/* istanbul ignore file */

var Results = (0, _reactInstantsearchDom.connectStateResults)(function (_ref) {
  var searchState = _ref.searchState,
      searchResults = _ref.searchResults,
      children = _ref.children;

  // welcome state
  if (searchState && !searchState.query) {
    return _react2.default.createElement(
      'div',
      { className: [_styleModule2.default.SearchResults, _styleModule2.default.SearchResults_empty].join(' ') },
      _react2.default.createElement('i', { className: 'icon icon-search' }),
      _react2.default.createElement(
        _Title2.default,
        { level: 6 },
        'Start typing to search\u2026'
      )
    );
  }

  // empty state (no results)
  if (searchResults && searchResults.nbHits === 0) {
    return _react2.default.createElement(
      'div',
      { className: [_styleModule2.default.SearchResults, _styleModule2.default.SearchResults_empty].join(' ') },
      _react2.default.createElement(
        _Title2.default,
        { level: 6 },
        'Try a different search.'
      ),
      _react2.default.createElement(
        'div',
        null,
        'No results for \u2018',
        searchState.query,
        '\u2019.'
      )
    );
  }

  return children;
});

var determineResultDisplay = function determineResultDisplay(hit) {
  var snippet = hit._snippetResult;

  var fullMatch = Object.entries(snippet).sort(function (a, b) {
    var aVal = a[1];
    var bVal = b[1];

    if (aVal.matchLevel === 'full' && (bVal.matchLevel === 'partial' || bVal.matchLevel === 'none')) return -1;else if (aVal.matchLevel === bVal.matchLevel) return 0;
    return 1;
  });
  return fullMatch[0][0];
};

var handleArrowFocus = function handleArrowFocus(e) {
  var key = e.key,
      target = e.target;

  var hitList = target.querySelector('.SearchResults-list') || target.parentElement;
  var focusAt = document.querySelector('a:focus');

  var focusTo = void 0;
  if (!focusAt) focusTo = hitList.firstElementChild.focus();else if (key && (key === 'ArrowUp' || key === 'ArrowDown')) {
    if (key === 'ArrowUp') focusTo = focusAt.previousElementSibling || hitList.lastElementChild;
    if (key === 'ArrowDown') focusTo = focusAt.nextElementSibling || hitList.firstElementChild;
    e.preventDefault();
  }

  if (focusTo) focusTo.focus();
};

var createCustomHitsComponent = function createCustomHitsComponent(subdomains, onReload, UrlManager) {
  var Hits = function Hits(_ref2) {
    var hits = _ref2.hits;

    // if there are no results within the current filters
    if (hits.length === 0) {
      return _react2.default.createElement(
        'div',
        { className: [_styleModule2.default.SearchResults, _styleModule2.default.SearchResults_empty].join(' ') },
        _react2.default.createElement(
          _Title2.default,
          { level: 6 },
          'No results.'
        ),
        _react2.default.createElement(
          'div',
          null,
          'Try a different filter or tab.'
        )
      );
    }

    // if there are results
    if (typeof onReload === 'function') onReload(); // callback
    var results = hits.map(function (hit) {
      // Build hitUrl
      var hitUrl = void 0;
      if (window.location.hash) {
        hitUrl = UrlManager.remove('hash', window.location.href);
      }
      hitUrl = UrlManager.upsert('slugs', hit.internalLink.split('/'), hitUrl);

      // Enterprise only: Populate child if project has parent & hit is from a different child project
      if (UrlManager.options.parent && subdomains[hit.project] !== UrlManager.options.project.subdomain) {
        hitUrl = UrlManager.upsert('child', subdomains[hit.project], hitUrl);
        // Remove version if hit is from a different child project
        if (UrlManager.options.version) {
          hitUrl = UrlManager.remove('version', hitUrl);
        }
      }

      var attribute = determineResultDisplay(hit);
      var title = hit.isReference && hit.method ? '(' + hit.method.toUpperCase() + ') ' + hit.title : hit.title;

      return _react2.default.createElement(
        'a',
        { key: hit.objectID, className: _styleModule2.default['SearchResults-Result'], href: hitUrl, tabIndex: 0 },
        _react2.default.createElement(
          'header',
          { className: _styleModule2.default['SearchResults-Result-Header'], title: title },
          hit.isReference && _react2.default.createElement(
            'span',
            {
              className: [_styleModule2.default['SearchResults-Method'], _styleModule2.default['SearchResults-Method_' + hit.method]].join(' ')
            },
            hit.method
          ),
          _react2.default.createElement(
            'span',
            { className: _styleModule2.default['SearchResults-Result-Title'] },
            hit.title,
            Object.keys(subdomains).length <= 1 || _react2.default.createElement(
              'span',
              { className: _styleModule2.default['SearchResults-Result-Project'] },
              hit.subdomain
            )
          ),
          hit.link_url && _react2.default.createElement(
            'small',
            { className: _styleModule2.default['SearchResults-Result-Link'] },
            _react2.default.createElement('i', { className: 'fa fa-external-link-alt' })
          )
        ),
        _react2.default.createElement(
          'div',
          { className: _styleModule2.default['SearchResults-Result-Excerpt'], title: title },
          _react2.default.createElement(_reactInstantsearchDom.Snippet, { attribute: attribute, hit: hit })
        )
      );
    });

    return _react2.default.createElement(
      'div',
      { className: [_styleModule2.default.SearchResults, _styleModule2.default.SearchResults_default].join(' ') },
      _react2.default.createElement('div', { className: _styleModule2.default['SearchResults-ScrollTo'] }),
      _react2.default.createElement(
        'div',
        { className: 'SearchResults-list', onKeyDownCapture: handleArrowFocus },
        results
      ),
      _react2.default.createElement(_Pagination2.default, null)
    );
  };
  Hits.propTypes = process.env.NODE_ENV !== "production" ? {
    hits: _propTypes2.default.array
  } : {};
  return Hits;
};

var SearchResults = function SearchResults(_ref3) {
  var subdomains = _ref3.subdomains,
      onReload = _ref3.onReload,
      UrlManager = _ref3.UrlManager;

  var Hits = createCustomHitsComponent(subdomains, onReload, UrlManager);
  var CustomHits = (0, _reactInstantsearchDom.connectHits)(Hits);
  return _react2.default.createElement(
    Results,
    null,
    _react2.default.createElement(CustomHits, { hitComponent: Hits })
  );
};

SearchResults.propTypes = process.env.NODE_ENV !== "production" ? {
  onReload: _propTypes2.default.func,
  subdomains: _propTypes2.default.object,
  tab: _propTypes2.default.string,
  UrlManager: _propTypes2.default.object
} : {};

SearchResults.defaultProps = {
  subdomains: {}
};

exports.default = SearchResults;
module.exports = exports['default'];