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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _cspaceRefname = require('cspace-refname');

var _ReadOnlyInput = require('./ReadOnlyInput');

var _ReadOnlyInput2 = _interopRequireDefault(_ReadOnlyInput);

var _FilteringDropdownMenuInput = require('./FilteringDropdownMenuInput');

var _FilteringDropdownMenuInput2 = _interopRequireDefault(_FilteringDropdownMenuInput);

var _QuickAdd = require('./QuickAdd');

var _QuickAdd2 = _interopRequireDefault(_QuickAdd);

var _parseAuthoritySpec = require('../helpers/parseAuthoritySpec');

var _parseAuthoritySpec2 = _interopRequireDefault(_parseAuthoritySpec);

var _pathHelpers = require('../helpers/pathHelpers');

var _AuthorityControlledInput = require('../../styles/cspace-input/AuthorityControlledInput.css');

var _AuthorityControlledInput2 = _interopRequireDefault(_AuthorityControlledInput);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var propTypes = _extends({}, _FilteringDropdownMenuInput2.default.propTypes, {
  addTerm: _react.PropTypes.func,
  authority: _react.PropTypes.string,
  findMatchingTerms: _react.PropTypes.func,
  formatMoreCharsRequiredMessage: _react.PropTypes.func,
  formatSearchResultMessage: _react.PropTypes.func,
  formatVocabName: _react.PropTypes.func,
  matches: _react.PropTypes.object,
  minLength: _react.PropTypes.number,
  recordTypes: _react.PropTypes.object,
  showQuickAdd: _react.PropTypes.bool,
  readOnly: _react.PropTypes.bool
});

var defaultProps = {
  formatMoreCharsRequiredMessage: function formatMoreCharsRequiredMessage() {
    return 'Continue typing to find matching terms';
  },
  formatSearchResultMessage: function formatSearchResultMessage(count) {
    var matches = count === 1 ? 'matching term' : 'matching terms';
    var num = count === 0 ? 'No' : count;

    return num + ' ' + matches + ' found';
  },
  // TODO: Make configurable
  minLength: 3,
  showQuickAdd: true
};

var getOptions = function getOptions(authority, matches, partialTerm) {
  var authorities = (0, _parseAuthoritySpec2.default)(authority);
  var options = [];

  if (matches) {
    (function () {
      var partialTermMatch = matches.get(partialTerm);

      if (partialTermMatch) {
        authorities.forEach(function (authoritySpec) {
          var authorityName = authoritySpec.authorityName,
              vocabularyName = authoritySpec.vocabularyName;


          var authorityMatch = partialTermMatch.getIn([authorityName, vocabularyName]);

          if (authorityMatch) {
            var items = authorityMatch.get('items');

            if (items) {
              var authorityOptions = items.map(function (item) {
                return {
                  value: item.refName,
                  label: item.termDisplayName
                };
              });

              options.push.apply(options, _toConsumableArray(authorityOptions));
            }
          }
        });
      }
    })();
  }

  return options;
};

var isPending = function isPending(authority, matches, partialTerm) {
  var authorities = (0, _parseAuthoritySpec2.default)(authority);
  var foundPending = false;

  if (matches) {
    (function () {
      var partialTermMatch = matches.get(partialTerm);

      if (partialTermMatch) {
        authorities.forEach(function (authoritySpec) {
          var authorityName = authoritySpec.authorityName,
              vocabularyName = authoritySpec.vocabularyName;


          var authorityMatch = partialTermMatch.getIn([authorityName, vocabularyName]);

          if (authorityMatch) {
            foundPending = foundPending || authorityMatch.get('isSearchPending') || authorityMatch.get('isAddPending');
          }
        });
      }
    })();
  }

  return foundPending;
};

var getNewTerm = function getNewTerm(authority, matches, partialTerm) {
  var authorities = (0, _parseAuthoritySpec2.default)(authority);

  var newTerm = null;

  if (matches) {
    (function () {
      var partialTermMatch = matches.get(partialTerm);

      if (partialTermMatch) {
        authorities.forEach(function (authoritySpec) {
          var authorityName = authoritySpec.authorityName,
              vocabularyName = authoritySpec.vocabularyName;


          var authorityMatch = partialTermMatch.getIn([authorityName, vocabularyName]);

          if (authorityMatch) {
            newTerm = newTerm || authorityMatch.get('newTerm');
          }
        });
      }
    })();
  }

  return newTerm;
};

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

  function AuthorityControlledInput(props) {
    _classCallCheck(this, AuthorityControlledInput);

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

    _this.findMatchingTerms = _this.findMatchingTerms.bind(_this);
    _this.handleDropdownInputCommit = _this.handleDropdownInputCommit.bind(_this);
    _this.handleDropdownInputRef = _this.handleDropdownInputRef.bind(_this);

    _this.state = {
      partialTerm: null,
      value: props.value
    };
    return _this;
  }

  _createClass(AuthorityControlledInput, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var newTerm = getNewTerm(nextProps.authority, nextProps.matches, this.state.partialTerm);

      var hadNewTerm = getNewTerm(this.props.authority, this.props.matches, this.state.partialTerm);

      if (newTerm && !hadNewTerm) {
        this.commit(newTerm.getIn(['document', 'ns2:collectionspace_core', 'refName']));
        this.dropdownInput.close();
      } else {
        var newState = {
          value: nextProps.value
        };

        if (!isPending(nextProps.authority, nextProps.matches, this.state.partialTerm)) {
          newState.options = getOptions(nextProps.authority, nextProps.matches, this.state.partialTerm);
        }

        this.setState(newState);
      }
    }
  }, {
    key: 'commit',
    value: function commit(value) {
      this.setState({
        options: [],
        partialTerm: null,
        value: value
      });

      var onCommit = this.props.onCommit;


      if (onCommit) {
        onCommit((0, _pathHelpers.getPath)(this.props), value);
      }
    }
  }, {
    key: 'findMatchingTerms',
    value: function findMatchingTerms(partialTerm) {
      var _props = this.props,
          authority = _props.authority,
          findMatchingTerms = _props.findMatchingTerms,
          matches = _props.matches,
          minLength = _props.minLength;


      var newState = {
        partialTerm: partialTerm
      };

      var searchNeeded = findMatchingTerms && partialTerm && partialTerm.length >= minLength && (!matches || !matches.has(partialTerm));

      if (searchNeeded) {
        // TODO: Pause to debounce
        findMatchingTerms(partialTerm);
      } else {
        newState.options = getOptions(authority, matches, partialTerm);
      }

      this.setState(newState);
    }
  }, {
    key: 'handleDropdownInputCommit',
    value: function handleDropdownInputCommit(path, value) {
      this.commit(value);
    }
  }, {
    key: 'handleDropdownInputRef',
    value: function handleDropdownInputRef(ref) {
      this.dropdownInput = ref;
    }
  }, {
    key: 'renderQuickAdd',
    value: function renderQuickAdd() {
      var _props2 = this.props,
          addTerm = _props2.addTerm,
          authority = _props2.authority,
          formatVocabName = _props2.formatVocabName,
          minLength = _props2.minLength,
          recordTypes = _props2.recordTypes,
          showQuickAdd = _props2.showQuickAdd;
      var partialTerm = this.state.partialTerm;


      if (showQuickAdd && partialTerm && partialTerm.length >= minLength) {
        return _react2.default.createElement(_QuickAdd2.default, {
          add: addTerm,
          authority: authority,
          displayName: partialTerm,
          formatVocabName: formatVocabName,
          recordTypes: recordTypes
        });
      }

      return null;
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          authority = _props3.authority,
          formatMoreCharsRequiredMessage = _props3.formatMoreCharsRequiredMessage,
          formatSearchResultMessage = _props3.formatSearchResultMessage,
          matches = _props3.matches,
          minLength = _props3.minLength,
          readOnly = _props3.readOnly,
          addTerm = _props3.addTerm,
          findMatchingTerms = _props3.findMatchingTerms,
          formatVocabName = _props3.formatVocabName,
          recordTypes = _props3.recordTypes,
          showQuickAdd = _props3.showQuickAdd,
          remainingProps = _objectWithoutProperties(_props3, ['authority', 'formatMoreCharsRequiredMessage', 'formatSearchResultMessage', 'matches', 'minLength', 'readOnly', 'addTerm', 'findMatchingTerms', 'formatVocabName', 'recordTypes', 'showQuickAdd']);

      var _state = this.state,
          options = _state.options,
          partialTerm = _state.partialTerm,
          value = _state.value;


      if (readOnly) {
        return _react2.default.createElement(_ReadOnlyInput2.default, { value: (0, _cspaceRefname.getDisplayName)(value) });
      }

      var moreCharsRequired = typeof partialTerm !== 'undefined' && partialTerm !== null && partialTerm.length < minLength;

      var formatStatusMessage = moreCharsRequired ? formatMoreCharsRequiredMessage : formatSearchResultMessage;

      var className = isPending(authority, matches, partialTerm) ? _AuthorityControlledInput2.default.searching : _AuthorityControlledInput2.default.normal;

      return _react2.default.createElement(_FilteringDropdownMenuInput2.default, _extends({}, remainingProps, {
        className: className,
        filter: this.findMatchingTerms,
        formatStatusMessage: formatStatusMessage,
        menuFooter: this.renderQuickAdd(),
        options: options,
        ref: this.handleDropdownInputRef,
        value: value,
        valueLabel: (0, _cspaceRefname.getDisplayName)(value),
        onCommit: this.handleDropdownInputCommit
      }));
    }
  }]);

  return AuthorityControlledInput;
}(_react.Component);

exports.default = AuthorityControlledInput;


AuthorityControlledInput.propTypes = propTypes;
AuthorityControlledInput.defaultProps = defaultProps;