'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 _get = require('lodash/get');

var _get2 = _interopRequireDefault(_get);

var _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _ErrorPage = require('./ErrorPage');

var _ErrorPage2 = _interopRequireDefault(_ErrorPage);

var _SearchForm = require('../search/SearchForm');

var _SearchForm2 = _interopRequireDefault(_SearchForm);

var _TitleBar = require('../sections/TitleBar');

var _TitleBar2 = _interopRequireDefault(_TitleBar);

var _configHelpers = require('../../helpers/configHelpers');

var _SearchPage = require('../../../styles/cspace-ui/SearchPage.css');

var _SearchPage2 = _interopRequireDefault(_SearchPage);

var _PageBody = require('../../../styles/cspace-ui/PageBody.css');

var _PageBody2 = _interopRequireDefault(_PageBody);

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 SearchForm = (0, _reactIntl.injectIntl)(_SearchForm2.default);

var messages = (0, _reactIntl.defineMessages)({
  title: {
    'id': 'searchPage.title',
    'defaultMessage': 'Search'
  }
});

var propTypes = {
  recordTypeValue: _propTypes2.default.string,
  vocabularyValue: _propTypes2.default.string,
  keywordValue: _propTypes2.default.string,
  advancedSearchCondition: _propTypes2.default.object,
  history: _propTypes2.default.object,
  location: _propTypes2.default.object,
  match: _propTypes2.default.object,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  onAdvancedSearchConditionCommit: _propTypes2.default.func,
  onKeywordCommit: _propTypes2.default.func,
  onRecordTypeCommit: _propTypes2.default.func,
  onVocabularyCommit: _propTypes2.default.func,
  onSearch: _propTypes2.default.func
};

var contextTypes = {
  config: _propTypes2.default.object.isRequired
};

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

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

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

    _this.handleRecordTypeCommit = _this.handleRecordTypeCommit.bind(_this);
    _this.handleVocabularyCommit = _this.handleVocabularyCommit.bind(_this);
    return _this;
  }

  _createClass(SearchPage, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.normalizePath();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      var historyChanged = false;

      var params = this.props.match.params;
      var prevParams = prevProps.match.params;


      if (params.recordType !== prevParams.recordType || params.vocabulary !== prevParams.vocabulary) {
        historyChanged = this.normalizePath();
      }

      if (!historyChanged) {
        // If the record type and/or vocab were changed via URL or by the selection of a default,
        // commit the new values.

        var searchDescriptor = this.getSearchDescriptor();
        var recordType = searchDescriptor.get('recordType');
        var vocabulary = searchDescriptor.get('vocabulary');

        var _props = this.props,
            recordTypeValue = _props.recordTypeValue,
            vocabularyValue = _props.vocabularyValue,
            onRecordTypeCommit = _props.onRecordTypeCommit,
            onVocabularyCommit = _props.onVocabularyCommit;


        if (recordType !== recordTypeValue || vocabulary !== vocabularyValue) {
          if (onRecordTypeCommit) {
            onRecordTypeCommit(recordType);
          }

          if (onVocabularyCommit) {
            var config = this.context.config;

            var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

            if ((0, _configHelpers.isAuthority)(recordTypeConfig)) {
              onVocabularyCommit(vocabulary);
            }
          }
        }
      }
    }
  }, {
    key: 'getSearchDescriptor',
    value: function getSearchDescriptor() {
      var params = this.props.match.params;


      var searchDescriptor = {};

      ['recordType', 'vocabulary'].forEach(function (param) {
        var value = params[param];

        if (typeof value !== 'undefined') {
          searchDescriptor[param] = value;
        }
      });

      return _immutable2.default.fromJS(searchDescriptor);
    }
  }, {
    key: 'normalizePath',
    value: function normalizePath() {
      var _props2 = this.props,
          recordTypeValue = _props2.recordTypeValue,
          vocabularyValue = _props2.vocabularyValue,
          history = _props2.history,
          location = _props2.location,
          match = _props2.match;
      var config = this.context.config;


      if (history) {
        var _match$params = match.params,
            recordType = _match$params.recordType,
            vocabulary = _match$params.vocabulary;


        if (!recordType) {
          recordType = recordTypeValue || (0, _configHelpers.getDefaultSearchRecordType)(config);
        }

        var recordTypeConfig = (0, _get2.default)(config, ['recordTypes', recordType]);

        if ((0, _configHelpers.isAuthority)(recordTypeConfig) && !vocabulary) {
          vocabulary = vocabularyValue || (0, _configHelpers.getDefaultSearchVocabulary)(recordTypeConfig);
        }

        var vocabularyPath = vocabulary ? '/' + vocabulary : '';
        var normalizedPath = '/search/' + recordType + vocabularyPath;

        if (normalizedPath !== location.pathname) {
          history.replace({
            pathname: normalizedPath
          });

          return true;
        }
      }

      return false;
    }
  }, {
    key: 'handleRecordTypeCommit',
    value: function handleRecordTypeCommit(value) {
      var _props3 = this.props,
          history = _props3.history,
          onRecordTypeCommit = _props3.onRecordTypeCommit;


      if (onRecordTypeCommit) {
        onRecordTypeCommit(value);
      }

      history.replace({
        pathname: '/search/' + value
      });
    }
  }, {
    key: 'handleVocabularyCommit',
    value: function handleVocabularyCommit(value) {
      var _props4 = this.props,
          history = _props4.history,
          onVocabularyCommit = _props4.onVocabularyCommit;


      if (onVocabularyCommit) {
        onVocabularyCommit(value);
      }

      var searchDescriptor = this.getSearchDescriptor();
      var recordType = searchDescriptor.get('recordType');

      history.replace({
        pathname: '/search/' + recordType + '/' + value
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props5 = this.props,
          advancedSearchCondition = _props5.advancedSearchCondition,
          keywordValue = _props5.keywordValue,
          perms = _props5.perms,
          onAdvancedSearchConditionCommit = _props5.onAdvancedSearchConditionCommit,
          onKeywordCommit = _props5.onKeywordCommit,
          onSearch = _props5.onSearch;
      var config = this.context.config;


      var searchDescriptor = this.getSearchDescriptor();
      var recordType = searchDescriptor.get('recordType');
      var vocabulary = searchDescriptor.get('vocabulary');

      var validation = (0, _configHelpers.validateLocation)(config, { recordType: recordType, vocabulary: vocabulary });

      if (validation.error) {
        return _react2.default.createElement(_ErrorPage2.default, { error: validation.error });
      }

      var title = _react2.default.createElement(_reactIntl.FormattedMessage, messages.title);

      return _react2.default.createElement(
        'div',
        { className: _SearchPage2.default.common },
        _react2.default.createElement(_TitleBar2.default, { title: title, updateDocumentTitle: true }),
        _react2.default.createElement(
          'div',
          { className: _PageBody2.default.common },
          _react2.default.createElement(SearchForm, {
            advancedSearchCondition: advancedSearchCondition,
            config: config,
            keywordValue: keywordValue,
            recordTypeValue: recordType,
            vocabularyValue: vocabulary,
            perms: perms,
            showButtons: true,
            onAdvancedSearchConditionCommit: onAdvancedSearchConditionCommit,
            onKeywordCommit: onKeywordCommit,
            onRecordTypeCommit: this.handleRecordTypeCommit,
            onVocabularyCommit: this.handleVocabularyCommit,
            onSearch: onSearch
          })
        )
      );
    }
  }]);

  return SearchPage;
}(_react.Component);

exports.default = SearchPage;


SearchPage.propTypes = propTypes;
SearchPage.contextTypes = contextTypes;