'use strict';

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

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 _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 _immutable = require('immutable');

var _immutable2 = _interopRequireDefault(_immutable);

var _cspaceInput = require('cspace-input');

var _MiniViewPopup = require('./MiniViewPopup');

var _MiniViewPopup2 = _interopRequireDefault(_MiniViewPopup);

var _AutocompleteInputContainer = require('../../containers/input/AutocompleteInputContainer');

var _AutocompleteInputContainer2 = _interopRequireDefault(_AutocompleteInputContainer);

var _permissionHelpers = require('../../helpers/permissionHelpers');

var _refNameHelpers = require('../../../src/helpers/refNameHelpers');

var _MiniViewPopupAutocompleteInput = require('../../../styles/cspace-ui/MiniViewPopupAutocompleteInput.css');

var _MiniViewPopupAutocompleteInput2 = _interopRequireDefault(_MiniViewPopupAutocompleteInput);

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; } /* global window */

var AutocompleteInput = _cspaceInput.baseComponents.AutocompleteInput;
var labelable = _cspaceInput.enhancers.labelable,
    repeatable = _cspaceInput.enhancers.repeatable;


var propTypes = Object.assign({}, AutocompleteInput.propTypes, {
  openDelay: _propTypes2.default.number,
  perms: _propTypes2.default.instanceOf(_immutable2.default.Map),
  clearRecord: _propTypes2.default.func
});

var defaultProps = {
  openDelay: 500
};

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

var BaseMiniViewPopupAutocompleteInput = exports.BaseMiniViewPopupAutocompleteInput = function (_Component) {
  _inherits(BaseMiniViewPopupAutocompleteInput, _Component);

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

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

    _this.handleDropdownClose = _this.handleDropdownClose.bind(_this);
    _this.handleDropdownOpen = _this.handleDropdownOpen.bind(_this);
    _this.handleItemMouseEnter = _this.handleItemMouseEnter.bind(_this);
    _this.handleItemMouseLeave = _this.handleItemMouseLeave.bind(_this);
    _this.handleMiniViewMouseEnter = _this.handleMiniViewMouseEnter.bind(_this);
    _this.handleMiniViewPopupDomRef = _this.handleMiniViewPopupDomRef.bind(_this);
    _this.handleMouseEnter = _this.handleMouseEnter.bind(_this);
    _this.handleMouseLeave = _this.handleMouseLeave.bind(_this);
    _this.handleRef = _this.handleRef.bind(_this);

    _this.state = {
      isOpen: false
    };
    return _this;
  }

  _createClass(BaseMiniViewPopupAutocompleteInput, [{
    key: 'componentWillUpdate',
    value: function componentWillUpdate(newProps) {
      if (newProps.value !== this.props.value) {
        this.close();
      }
    }
  }, {
    key: 'cancelClose',
    value: function cancelClose() {
      if (this.closeTimer) {
        window.clearTimeout(this.closeTimer);

        this.openTimer = null;
      }
    }
  }, {
    key: 'cancelOpen',
    value: function cancelOpen() {
      if (this.openTimer) {
        window.clearTimeout(this.openTimer);

        this.openTimer = null;
      }
    }
  }, {
    key: 'close',
    value: function close() {
      this.cancelOpen();
      this.cancelClose();

      if (this.domNode && this.state.isOpen) {
        this.setState({
          isOpen: false,
          value: null,
          element: null
        });
      }
    }
  }, {
    key: 'open',
    value: function open(value, element) {
      this.cancelOpen();
      this.cancelClose();

      this.setState({
        isOpen: true,
        value: value,
        element: element
      });
    }
  }, {
    key: 'handleDropdownClose',
    value: function handleDropdownClose() {
      this.close();

      this.state = {
        isFiltering: false
      };
    }
  }, {
    key: 'handleDropdownOpen',
    value: function handleDropdownOpen() {
      this.close();

      this.setState({
        isFiltering: true
      });
    }
  }, {
    key: 'handleItemMouseEnter',
    value: function handleItemMouseEnter(value, element) {
      var _this2 = this;

      this.cancelClose();

      this.openTimer = setTimeout(function () {
        _this2.open(value, element);
      }, this.props.openDelay);
    }
  }, {
    key: 'handleItemMouseLeave',
    value: function handleItemMouseLeave() {
      var _this3 = this;

      this.cancelOpen();

      this.closeTimer = window.setTimeout(function () {
        _this3.close();
      }, this.props.openDelay);
    }
  }, {
    key: 'handleMiniViewMouseEnter',
    value: function handleMiniViewMouseEnter() {
      this.cancelClose();
      this.cancelOpen();
    }
  }, {
    key: 'handleMiniViewPopupDomRef',
    value: function handleMiniViewPopupDomRef(ref) {
      this.miniViewPopupDomNode = ref;
    }
  }, {
    key: 'handleMouseEnter',
    value: function handleMouseEnter() {
      var _this4 = this;

      var _state = this.state,
          isFiltering = _state.isFiltering,
          isOpen = _state.isOpen;


      if (!isFiltering && !isOpen) {
        this.openTimer = setTimeout(function () {
          _this4.open(_this4.props.value);
        }, this.props.openDelay);
      }
    }
  }, {
    key: 'handleMouseLeave',
    value: function handleMouseLeave() {
      this.close();
    }
  }, {
    key: 'handleRef',
    value: function handleRef(ref) {
      this.domNode = ref;
    }
  }, {
    key: 'renderMiniViewPopup',
    value: function renderMiniViewPopup() {
      var _state2 = this.state,
          isOpen = _state2.isOpen,
          value = _state2.value,
          element = _state2.element;


      if (!value || !isOpen) {
        return undefined;
      }

      var perms = this.props.perms;
      var config = this.context.config;


      var csid = (0, _refNameHelpers.refNameToCsid)(value);
      var recordType = (0, _refNameHelpers.getRecordType)(config, value);
      var vocabulary = (0, _refNameHelpers.getVocabulary)(config, value);

      if (!recordType || !csid) {
        return undefined;
      }

      if (!(0, _permissionHelpers.canRead)(recordType, perms)) {
        return undefined;
      }

      var style = void 0;

      if (element) {
        var inputRect = this.domNode.getBoundingClientRect();
        var itemRect = element.getBoundingClientRect();

        style = {
          left: itemRect.width,
          top: itemRect.top - inputRect.top - inputRect.height
        };
      }

      return _react2.default.createElement(_MiniViewPopup2.default, {
        config: config,
        recordType: recordType,
        vocabulary: vocabulary,
        csid: csid,
        style: style,
        domRef: this.handleMiniViewPopupDomRef,
        onMouseEnter: this.handleMiniViewMouseEnter
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var _props = this.props,
          openDelay = _props.openDelay,
          perms = _props.perms,
          clearRecord = _props.clearRecord,
          remainingProps = _objectWithoutProperties(_props, ['openDelay', 'perms', 'clearRecord']);

      if (this.props.asText) {
        return _react2.default.createElement(_AutocompleteInputContainer2.default, remainingProps);
      }

      var isFiltering = this.state.isFiltering;


      var className = this.props.embedded ? _MiniViewPopupAutocompleteInput2.default.embedded : _MiniViewPopupAutocompleteInput2.default.normal;

      var popup = void 0;
      var filteringPopup = void 0;

      if (isFiltering) {
        filteringPopup = this.renderMiniViewPopup();
      } else {
        popup = this.renderMiniViewPopup();
      }

      return _react2.default.createElement(
        'div',
        {
          className: className,
          ref: this.handleRef,
          onMouseEnter: this.handleMouseEnter,
          onMouseLeave: this.handleMouseLeave
        },
        _react2.default.createElement(_AutocompleteInputContainer2.default, _extends({}, remainingProps, {
          onClose: this.handleDropdownClose,
          onOpen: this.handleDropdownOpen,
          onItemMouseEnter: this.handleItemMouseEnter,
          onItemMouseLeave: this.handleItemMouseLeave,
          menuFooter: filteringPopup
        })),
        popup
      );
    }
  }]);

  return BaseMiniViewPopupAutocompleteInput;
}(_react.Component);

BaseMiniViewPopupAutocompleteInput.propTypes = propTypes;
BaseMiniViewPopupAutocompleteInput.defaultProps = defaultProps;
BaseMiniViewPopupAutocompleteInput.contextTypes = contextTypes;

exports.default = repeatable(labelable(BaseMiniViewPopupAutocompleteInput));