'use strict';

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

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _class, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactImmutableProptypes = require('react-immutable-proptypes');

var _reactImmutableProptypes2 = _interopRequireDefault(_reactImmutableProptypes);

var _immutable = require('immutable');

var _Button = require('@instructure/ui-buttons/lib/components/Button');

var _Button2 = _interopRequireDefault(_Button);

var _MenuItem = require('@instructure/ui-menu/lib/components/Menu/MenuItem');

var _MenuItem2 = _interopRequireDefault(_MenuItem);

var _Menu = require('@instructure/ui-menu/lib/components/Menu');

var _Menu2 = _interopRequireDefault(_Menu);

var _ScreenReaderContent = require('@instructure/ui-a11y/lib/components/ScreenReaderContent');

var _ScreenReaderContent2 = _interopRequireDefault(_ScreenReaderContent);

var _IconArrowDownLine = require('instructure-icons/lib/Line/IconArrowDownLine');

var _IconArrowDownLine2 = _interopRequireDefault(_IconArrowDownLine);

var _IconArrowUpLine = require('instructure-icons/lib/Line/IconArrowUpLine');

var _IconArrowUpLine2 = _interopRequireDefault(_IconArrowUpLine);

var _IconDragHandleLine = require('instructure-icons/lib/Line/IconDragHandleLine');

var _IconDragHandleLine2 = _interopRequireDefault(_IconDragHandleLine);

var _IconMiniArrowDownLine = require('instructure-icons/lib/Line/IconMiniArrowDownLine');

var _IconMiniArrowDownLine2 = _interopRequireDefault(_IconMiniArrowDownLine);

var _IconMiniArrowUpLine = require('instructure-icons/lib/Line/IconMiniArrowUpLine');

var _IconMiniArrowUpLine2 = _interopRequireDefault(_IconMiniArrowUpLine);

var _formatMessage = require('../../../../format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _keyboardClickable = require('../../../../../common/util/keyboardClickable');

var _keyboardClickable2 = _interopRequireDefault(_keyboardClickable);

var _constants = require('../../../../../constants');

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

var DragHandle = (_temp2 = _class = function (_Component) {
  (0, _inherits3.default)(DragHandle, _Component);

  function DragHandle() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3.default)(this, DragHandle);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = DragHandle.__proto__ || Object.getPrototypeOf(DragHandle)).call.apply(_ref, [this].concat(args))), _this), _this.moveUp = function () {
      _this.moveToPosition(_this.props.quizEntry.position - 1);
      var msg = 'Objekt um eine Position nach oben verschoben';
      _this.props.screenreaderNotification(msg);
    }, _this.moveDown = function () {
      _this.moveToPosition(_this.props.quizEntry.position + 1);
      var msg = 'Objekt um eine Position nach unten verschoben';
      _this.props.screenreaderNotification(msg);
    }, _this.moveToTop = function () {
      _this.moveQuizEntry(1, '');
      var msg = 'Objekt an den Anfang des Leistungstests verschoben';
      _this.props.screenreaderNotification(msg);
    }, _this.moveToBottom = function () {
      _this.moveQuizEntry(_this.props.quizEntries.size, '');
      var msg = 'Objekt ans Ende des Leistungstests verschoben';
      _this.props.screenreaderNotification(msg);
    }, _this.handleTriggerRef = function (node) {
      _this.triggerRef = node;
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(DragHandle, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.conditionalFocus();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      this.conditionalFocus();
    }
  }, {
    key: 'conditionalFocus',
    value: function conditionalFocus() {
      var matchingQuizEntryId = this.props.movedQuizEntry === this.props.quizEntry.id;
      var matchingLocation = this.props.onSidebar === this.props.movedInSidebar;
      if (matchingQuizEntryId && matchingLocation) {
        this.triggerRef && this.triggerRef.focus();
        this.props.clearUI(_constants.MOVED_QUIZ_ENTRY);
        this.props.clearUI(_constants.MOVED_IN_SIDEBAR);
      }
    }
  }, {
    key: 'isFirstItem',
    value: function isFirstItem() {
      return this.props.quizEntry.position === 1;
    }
  }, {
    key: 'isLastItem',
    value: function isLastItem() {
      var _props = this.props,
          quizEntry = _props.quizEntry,
          quizEntries = _props.quizEntries;

      var numItems = quizEntry.hasStimulus ? quizEntry.getNestedEntries().size : 0;
      var position = quizEntry.position + numItems;
      return position === quizEntries.size;
    }
  }, {
    key: 'handleMove',
    value: function handleMove(position, stimulusQuizEntryId) {
      var _props2 = this.props,
          quizEntry = _props2.quizEntry,
          quizId = _props2.quizId;

      var stimulusQuizEntryIdChanged = stimulusQuizEntryId !== quizEntry.stimulusQuizEntryId;
      var isImmutable = quizEntry.isItem ? quizEntry.getEntry().isImmutable() : false;
      if (isImmutable && stimulusQuizEntryIdChanged) {
        var uiData = (0, _immutable.Map)({
          movedInSidebar: this.props.onSidebar,
          quizId: quizId,
          position: position,
          stimulusQuizEntryId: stimulusQuizEntryId,
          quizEntryId: quizEntry.id
        });
        this.props.setUI(_constants.MOVE_IMMUTABLE_DATA, uiData);
        this.props.openMoveImmutableModal();
      } else {
        this.props.setUI(_constants.MOVED_IN_SIDEBAR, this.props.onSidebar);
        this.props.moveQuizEntry(quizId, position, stimulusQuizEntryId, quizEntry.id);
      }
    }
  }, {
    key: 'moveQuizEntry',
    value: function moveQuizEntry(position, stimulusQuizEntryId) {
      this.props.quizEntry.isTemporary ? this.props.moveTemporaryQuizEntry(position, stimulusQuizEntryId) : this.handleMove(position, stimulusQuizEntryId);
    }
  }, {
    key: 'moveToPosition',
    value: function moveToPosition(position) {
      var quizEntry = this.props.quizEntry;

      var movingDown = position > quizEntry.position;
      var newPosition = position;
      if (movingDown && quizEntry.hasStimulus) {
        newPosition = position + quizEntry.getNestedEntries().size;
      }
      var targetQuizEntry = this.props.quizEntries.find(function (qe) {
        return qe.position === newPosition;
      });

      if (targetQuizEntry === void 0) {
        var newPos = movingDown ? this.props.quizEntries.size : 1;
        this.moveQuizEntry(newPos, '');
        return;
      }

      var inStimulus = quizEntry.isInStimulus;
      var targetInStimulus = targetQuizEntry.isInStimulus;
      var losingStimulusQuizEntryId = inStimulus && !targetInStimulus;
      var receivingStimulusQuizEntryId = !inStimulus && targetInStimulus;
      var newStimulusQuizEntryId = quizEntry.stimulusQuizEntryId;

      // Handling moving of stimulus groups:
      if (quizEntry.hasStimulus) {
        if (movingDown && targetQuizEntry.hasStimulus) {
          newPosition += targetQuizEntry.getNestedEntries().size;
        } else if (!movingDown && targetInStimulus) {
          var targetStimulusQuizEntry = this.props.quizEntries.find(function (qe) {
            return qe.id === targetQuizEntry.stimulusQuizEntryId;
          });
          newPosition = position - targetStimulusQuizEntry.getNestedEntries().size;
        }

        // This block is for handling moving of items in/out/around stimuli.
        // For example, when moving down, out of a stimulus group, you don't actually
        // want the position of the quizEntry to change, you just want to change the
        // stimulusQuizEntryId, so that it's no longer associated with the stimulus.
        // There are 4 such cases:
      } else if (targetQuizEntry.hasStimulus && !inStimulus) {
        newPosition = movingDown ? position : position + 1;
        newStimulusQuizEntryId = targetQuizEntry.id;
      } else if (targetQuizEntry.hasStimulus && inStimulus) {
        newPosition = movingDown ? position - 1 : position;
        newStimulusQuizEntryId = '';
      } else if (receivingStimulusQuizEntryId && !movingDown) {
        newPosition = position + 1;
        newStimulusQuizEntryId = targetQuizEntry.stimulusQuizEntryId;
      } else if (losingStimulusQuizEntryId && movingDown) {
        newPosition = position - 1;
        newStimulusQuizEntryId = '';
      }
      this.moveQuizEntry(newPosition, newStimulusQuizEntryId);
    }
  }, {
    key: 'renderIcon',
    value: function renderIcon() {
      var displayPosition = this.props.quizEntry.positionToDisplay(this.props.displayPosition);
      return (
        // NOTE: `cursor="move"` doesn't work yet.
        // See https://instructure.atlassian.net/browse/INSTUI-1410
        _react2.default.createElement(
          _Button2.default,
          {
            as: 'div',
            variant: 'icon',
            icon: _IconDragHandleLine2.default,
            size: 'small',
            ref: this.handleTriggerRef,
            onKeyDown: _keyboardClickable2.default,
            disabled: this.props.disabled,
            'data-automation': 'sdk-drag-handle',
            cursor: 'move'
          },
          _react2.default.createElement(
            _ScreenReaderContent2.default,
            null,
            this.props.quizEntry.generateScreenReaderText(displayPosition, _constants.MOVE)
          )
        )
      );
    }
  }, {
    key: 'renderMenuItems',
    value: function renderMenuItems() {
      var menuItems = [];
      if (!this.isFirstItem()) {
        menuItems.push(_react2.default.createElement(
          _MenuItem2.default,
          { key: 'toTop', onSelect: this.moveToTop },
          _react2.default.createElement(_IconArrowUpLine2.default, null),
          'An den Anfang verschieben'
        ));
        menuItems.push(_react2.default.createElement(
          _MenuItem2.default,
          { key: 'moveUp', onSelect: this.moveUp },
          _react2.default.createElement(_IconMiniArrowUpLine2.default, null),
          'Nach oben verschieben'
        ));
      }
      if (!this.isLastItem() || this.props.quizEntry.isInStimulus) {
        menuItems.push(_react2.default.createElement(
          _MenuItem2.default,
          { key: 'moveDown', onSelect: this.moveDown },
          _react2.default.createElement(_IconMiniArrowDownLine2.default, null),
          'Nach unten verschieben'
        ));
        menuItems.push(_react2.default.createElement(
          _MenuItem2.default,
          { key: 'toBottom', onSelect: this.moveToBottom },
          _react2.default.createElement(_IconArrowDownLine2.default, null),
          'Ans Ende verschieben'
        ));
      }
      return menuItems;
    }
  }, {
    key: 'render',
    value: function render() {
      var menuItems = this.renderMenuItems();
      if (!this.props.disabled && menuItems.length > 0) {
        return _react2.default.createElement(
          _Menu2.default,
          {
            trigger: this.renderIcon(),
            onToggle: this.setFocused,
            mountNode: this.props.onSidebar ? this.sidebarNav : void 0,
            placement: this.props.onSidebar ? 'start' : void 0
          },
          menuItems
        );
      }
      return this.renderIcon();
    }
  }, {
    key: 'sidebarNav',
    get: function get() {
      return document.getElementById(_constants.SIDEBAR_NAV_ID);
    }
  }]);
  DragHandle.displayName = 'DragHandle'
  ;
  return DragHandle;
}(_react.Component), _class.propTypes = {
  clearUI: _propTypes2.default.func.isRequired,
  disabled: _propTypes2.default.bool,
  displayPosition: _propTypes2.default.number.isRequired,
  moveTemporaryQuizEntry: _propTypes2.default.func.isRequired,
  moveQuizEntry: _propTypes2.default.func.isRequired,
  movedInSidebar: _propTypes2.default.bool,
  movedQuizEntry: _propTypes2.default.string,
  onSidebar: _propTypes2.default.bool,
  openMoveImmutableModal: _propTypes2.default.func.isRequired,
  quizEntry: _reactImmutableProptypes2.default.record.isRequired,
  quizEntries: _reactImmutableProptypes2.default.listOf(_reactImmutableProptypes2.default.record).isRequired,
  quizId: _propTypes2.default.string.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  setUI: _propTypes2.default.func.isRequired
}, _class.defaultProps = {
  disabled: false,
  movedQuizEntry: '',
  movedInSidebar: null,
  onSidebar: false
}, _temp2);
exports.default = DragHandle;