'use strict';

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

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

const SearchForm = (0, _reactIntl.injectIntl)(_SearchForm2.default);

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

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

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

class SearchPage extends _react.Component {
  constructor() {
    super();

    this.handleRecordTypeCommit = this.handleRecordTypeCommit.bind(this);
    this.handleVocabularyCommit = this.handleVocabularyCommit.bind(this);
  }

  componentDidMount() {
    this.normalizePath();
  }

  componentDidUpdate(prevProps) {
    let historyChanged = false;

    const params = this.props.match.params;
    const 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.

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

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


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

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

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

          if ((0, _configHelpers.isAuthority)(recordTypeConfig)) {
            onVocabularyCommit(vocabulary);
          }
        }
      }
    }
  }

  getSearchDescriptor() {
    const params = this.props.match.params;


    const searchDescriptor = {};

    ['recordType', 'vocabulary'].forEach(param => {
      const value = params[param];

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

    return _immutable2.default.fromJS(searchDescriptor);
  }

  normalizePath() {
    var _props2 = this.props;
    const recordTypeValue = _props2.recordTypeValue,
          vocabularyValue = _props2.vocabularyValue,
          history = _props2.history,
          location = _props2.location,
          match = _props2.match;
    const config = this.context.config;


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


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

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

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

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

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

        return true;
      }
    }

    return false;
  }

  handleRecordTypeCommit(value) {
    var _props3 = this.props;
    const history = _props3.history,
          onRecordTypeCommit = _props3.onRecordTypeCommit;


    if (onRecordTypeCommit) {
      onRecordTypeCommit(value);
    }

    history.replace({
      pathname: `/search/${value}`
    });
  }

  handleVocabularyCommit(value) {
    var _props4 = this.props;
    const history = _props4.history,
          onVocabularyCommit = _props4.onVocabularyCommit;


    if (onVocabularyCommit) {
      onVocabularyCommit(value);
    }

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

    history.replace({
      pathname: `/search/${recordType}/${value}`
    });
  }

  render() {
    var _props5 = this.props;
    const advancedSearchCondition = _props5.advancedSearchCondition,
          keywordValue = _props5.keywordValue,
          perms = _props5.perms,
          onAdvancedSearchConditionCommit = _props5.onAdvancedSearchConditionCommit,
          onKeywordCommit = _props5.onKeywordCommit,
          onSearch = _props5.onSearch;
    const config = this.context.config;


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

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

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

    const 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
        })
      )
    );
  }
}

exports.default = SearchPage;
SearchPage.propTypes = propTypes;
SearchPage.contextTypes = contextTypes;