'use strict';

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

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

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _SearchResultItemLink = require('./SearchResultItemLink');

var _SearchResultItemLink2 = _interopRequireDefault(_SearchResultItemLink);

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 messages = (0, _reactIntl.defineMessages)({
  pending: {
    'id': 'searchResultLink.pending',
    'defaultMessage': '...'
  },
  error: {
    'id': 'searchResultLink.error',
    'defaultMessage': '...'
  },
  notFound: {
    'id': 'searchResultLink.notFound',
    'defaultMessage': '[record not found]'
  },
  label: {
    'id': 'searchResultLink.label',
    'defaultMessage': '{recordNumber}'
  }
});

var propTypes = {
  config: _propTypes2.default.object,
  listType: _propTypes2.default.string,
  search: _propTypes2.default.func,
  searchName: _propTypes2.default.string,
  searchDescriptor: _propTypes2.default.instanceOf(_immutable2.default.Map),
  itemFilter: _propTypes2.default.func,
  isSearchPending: _propTypes2.default.bool,
  searchError: _propTypes2.default.instanceOf(_immutable2.default.Map),
  searchResult: _propTypes2.default.instanceOf(_immutable2.default.Map)
};

var defaultProps = {
  listType: 'common',
  itemFilter: function itemFilter() {
    return true;
  }
};

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

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

    return _possibleConstructorReturn(this, (SearchResultLink.__proto__ || Object.getPrototypeOf(SearchResultLink)).apply(this, arguments));
  }

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


      if (searchName !== prevSearchName || !_immutable2.default.is(searchDescriptor, prevSearchDescriptor)) {
        this.search();
      }
    }
  }, {
    key: 'getResultItem',
    value: function getResultItem() {
      var _props2 = this.props,
          config = _props2.config,
          searchResult = _props2.searchResult,
          itemFilter = _props2.itemFilter,
          listType = _props2.listType;
      var _config$listTypes$lis = config.listTypes[listType],
          listNodeName = _config$listTypes$lis.listNodeName,
          itemNodeName = _config$listTypes$lis.itemNodeName;


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

      if (isNaN(totalItems) || totalItems === 0) {
        return null;
      }

      var items = list.get(itemNodeName);

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

      return items.find(itemFilter);
    }
  }, {
    key: 'search',
    value: function search() {
      var _props3 = this.props,
          config = _props3.config,
          search = _props3.search,
          searchName = _props3.searchName,
          searchDescriptor = _props3.searchDescriptor;


      if (search) {
        search(config, searchName, searchDescriptor);
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props4 = this.props,
          config = _props4.config,
          isSearchPending = _props4.isSearchPending,
          searchError = _props4.searchError,
          searchResult = _props4.searchResult;


      if (isSearchPending) {
        return _react2.default.createElement(_reactIntl.FormattedMessage, messages.pending);
      }

      if (searchResult) {
        var item = this.getResultItem();

        if (item) {
          return _react2.default.createElement(_SearchResultItemLink2.default, {
            config: config,
            item: item,
            message: messages.label
          });
        }

        return _react2.default.createElement(_reactIntl.FormattedMessage, messages.notFound);
      }

      if (searchError) {
        return _react2.default.createElement(_reactIntl.FormattedMessage, messages.error);
      }

      return null;
    }
  }]);

  return SearchResultLink;
}(_react.Component);

exports.default = SearchResultLink;


SearchResultLink.propTypes = propTypes;
SearchResultLink.defaultProps = defaultProps;