"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.QuizEntryEditRaw = exports.UndecoratedQuizEntryEdit = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf3 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

var _reactDnd = require("react-dnd");

var _pick = _interopRequireDefault(require("lodash/pick"));

var _first = _interopRequireDefault(require("lodash/first"));

var _lib = _interopRequireDefault(require("@instructure/ui-themeable/lib"));

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-common/lib/format-message"));

var _CustomPropTypes = _interopRequireDefault(require("../../../../../common/util/CustomPropTypes"));

var _ElementsForSelectors = _interopRequireDefault(require("../../../../../common/util/ElementsForSelectors"));

var _AddToBankModal = _interopRequireDefault(require("../../../../../banks/components/AddToBankModal"));

var _DragAndDropZone = _interopRequireDefault(require("../../../../../common/components/shared/drag_and_drop/DragAndDropZone"));

var _componentWithOutsideClick = _interopRequireDefault(require("../../../../../common/components/shared/functionality/componentWithOutsideClick"));

var _Header = _interopRequireDefault(require("./Header"));

var _Footer = _interopRequireDefault(require("./Footer"));

var _constants = require("@instructure/quiz-common/lib/constants");

var _dragAndDropUtils = require("../../../../../common/components/shared/drag_and_drop/dragAndDropUtils");

var _theme = _interopRequireDefault(require("./theme"));

var _dec,
    _class,
    _class2,
    _temp,
    _default_pl_number = Intl.NumberFormat("pl", { style: "decimal" }).format;

var styles = {
  componentId: 'cpaVF',
  template: function template(theme) {
    return "\n\n.cpaVF_qRLg{font-size:".concat(theme.quizEntryEditFontSize || 'inherit', ";padding:").concat(theme.quizEntryEditPadding || 'inherit', " 0;position:relative;transform:translateZ(0);z-index:3333}");
  },
  'quizEntryEdit': 'cpaVF_qRLg'
};
var QuizEntryEdit = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(QuizEntryEdit, _Component);

  function QuizEntryEdit() {
    var _getPrototypeOf2;

    var _this;

    (0, _classCallCheck2.default)(this, QuizEntryEdit);

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

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(QuizEntryEdit)).call.apply(_getPrototypeOf2, [this].concat(args)));
    _this.state = {
      canSubmit: true
    };

    _this.onSubmit = function (e) {
      var displayPosition = _this.props.displayPosition;
      e && e.preventDefault();

      if (_this.isValid() && _this.state.canSubmit) {
        _this.successfulSubmit();
      } else {
        var msg = "Elementu " + _default_pl_number(displayPosition) + " nie mo\u017Cna zapisa\u0107 z powodu nieprawid\u0142owych danych wej\u015Bcia.";

        _this.props.screenreaderNotification(msg);

        _this.props.showError(_this.props.guid);

        _this.props.clearNextQuizEntry();
      }
    };

    _this.createOrUpdateItem = function () {
      var workingEntry = _this.props.workingEntry;

      if (_this.props.entry.isTemporary()) {
        return _this.props.createItem(workingEntry, _this.props.quizId, 'quiz');
      } else if (_this.props.shouldClone) {
        return _this.props.createItem(workingEntry, _this.props.quizId, 'quiz', workingEntry.id);
      } else if (_this.props.entry.hasModifications()) {
        return _this.props.updateItem(workingEntry, _this.props.quizId, 'quiz');
      }

      return Promise.resolve(_this.props.entry.toJS());
    };

    _this.createNextQuizEntry = function () {
      var _this$props$nextQuizE = _this.props.nextQuizEntry,
          interactionTypeData = _this$props$nextQuizE.interactionTypeData,
          quizId = _this$props$nextQuizE.quizId,
          position = _this$props$nextQuizE.position,
          stimulusId = _this$props$nextQuizE.stimulusId,
          parentEntryId = _this$props$nextQuizE.parentEntryId;

      if (!interactionTypeData) {
        _this.props.createTempStimulus(quizId, position);
      } else {
        var defaultInteractionData = interactionTypeData.getDefaultInteractionData();
        var scoringData = interactionTypeData.getDefaultScoringData(defaultInteractionData);

        _this.props.createTempItem(quizId, position, {
          id: interactionTypeData.id,
          interactionData: defaultInteractionData,
          itemBody: interactionTypeData.itemBody,
          properties: interactionTypeData.defaultProperties,
          scoringAlgorithm: (0, _first.default)(interactionTypeData.scoringAlgorithmOptions),
          scoringData: scoringData,
          userResponseType: (0, _first.default)(interactionTypeData.userResponseTypeOptions)
        }, parentEntryId, stimulusId);
      }

      _this.props.clearNextQuizEntry();
    };

    _this.createOrUpdateQuizEntry = function (itemData) {
      var _this$props = _this.props,
          workingEntry = _this$props.workingEntry,
          workingQuizEntry = _this$props.workingQuizEntry,
          quizEntry = _this$props.quizEntry,
          shouldClone = _this$props.shouldClone;

      if (workingQuizEntry.isTemporary) {
        return _this.props.createQuizEntry(_this.props.quizId, workingEntry.id === _constants.TEMPORARY_ITEM_ID ? itemData.id : workingEntry.id, workingQuizEntry.entryType, workingQuizEntry.getProperties());
      } else if (shouldClone && (!quizEntry.isBankEntry || quizEntry.isArchivedBankEntry)) {
        return _this.props.cloneQuizEntry(_this.props.quizId, workingQuizEntry.id, Object.assign({}, workingQuizEntry.toJS(), {
          entryId: itemData.id,
          entryType: quizEntry.isArchivedBankEntry ? quizEntry.getEntry().entryType : quizEntry.entryType
        }));
      } else if (_this.props.quizEntry.hasModifications()) {
        // if a quiz entry is a bank entry, item.id is not bank entry id
        // if a quiz entry is not a bank entry, item.id is entry id
        var entryId = quizEntry.isBankEntry ? workingQuizEntry.entry.get('id') : itemData.id;
        return _this.props.updateQuizEntry(_this.props.quizId, workingQuizEntry.id, Object.assign({}, workingQuizEntry.toJS(), {
          entryId: entryId
        }));
      }

      return Promise.resolve(_this.props.quizEntry);
    };

    _this.successfulSubmit =
    /*#__PURE__*/
    (0, _asyncToGenerator2.default)(
    /*#__PURE__*/
    _regenerator.default.mark(function _callee() {
      var itemData;
      return _regenerator.default.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              _this.setState({
                canSubmit: false
              });

              _context.prev = 1;
              _context.next = 4;
              return _this.createOrUpdateItem();

            case 4:
              itemData = _context.sent;
              _context.next = 7;
              return _this.createOrUpdateQuizEntry(itemData);

            case 7:
              _context.next = 13;
              break;

            case 9:
              _context.prev = 9;
              _context.t0 = _context["catch"](1);

              _this.setState({
                canSubmit: true
              });

              throw _context.t0;

            case 13:
              _this.props.hideError(_this.props.guid);

              _this.props.clearTemporaryItem(_this.props.quizId);

              if (_this.props.shouldClone) {
                _this.props.openRegradeModal();
              }

              _this.clearModifications();

              if (_this.props.nextQuizEntry) {
                _this.createNextQuizEntry();
              }

              _this.props.switchOffEditing();

            case 19:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[1, 9]]);
    }));

    _this.clearChanges = function () {
      _this.clearModifications();

      if (_this.props.quizEntry.isTemporary) {
        _this.props.clearTemporaryItem(_this.props.quizId);

        _this.props.setUi(_constants.DELETED_QUIZ_ENTRY, {
          position: Math.ceil(_this.props.quizEntry.position),
          inStimulus: _this.props.quizEntry.hasStimulus
        });
      }
    };

    _this.handleAddToBankContinue = function () {
      if (_this.props.workingQuizEntry.isTemporary) {
        _this.setState({
          canSubmit: false
        });
      }
    };

    _this.handleAddToBank = function (bankEntry) {
      var workingQuizEntry = _this.props.workingQuizEntry;

      if (workingQuizEntry.isTemporary) {
        _this.props.createQuizEntry(_this.props.quizId, bankEntry.id, 'BankEntry', workingQuizEntry.getProperties());

        _this.props.clearTemporaryItem(_this.props.quizId);

        _this.clearModifications();

        _this.props.switchOffEditing();
      } else if (_this.props.shouldClone) {
        _this.props.cloneQuizEntry(_this.props.quizId, workingQuizEntry.id, Object.assign({}, workingQuizEntry.toJS(), {
          entryId: bankEntry.id,
          entryType: 'BankEntry'
        }));
      } else {
        _this.props.updateQuizEntry(_this.props.quizId, workingQuizEntry.id, {
          entryId: bankEntry.id,
          entryType: 'BankEntry'
        });
      }
    };

    _this.getEntryForBank = function () {
      var _this$props2 = _this.props,
          entry = _this$props2.entry,
          workingEntry = _this$props2.workingEntry,
          quizId = _this$props2.quizId,
          shouldClone = _this$props2.shouldClone;

      if (entry.isTemporary()) {
        return _this.props.createItem(workingEntry, quizId);
      } else if (entry.hasModifications()) {
        if (shouldClone) {
          return _this.props.createItem(workingEntry, quizId);
        } else {
          return _this.props.updateItem(workingEntry, quizId);
        }
      } else {
        return Promise.resolve(entry);
      }
    };

    _this.connectDragSource = function (dragHandle) {
      return _this.props.connectDragSource(dragHandle);
    };

    _this.clearModifications = function () {
      _this.props.clearModifications('items', _this.props.entry.id);

      _this.props.clearModifications('quizEntries', _this.props.quizEntry.id);
    };

    _this.renderDraggable = function () {
      var _this$props3 = _this.props,
          connectDragPreview = _this$props3.connectDragPreview,
          draggingOver = _this$props3.draggingOver,
          draggingAboveHalf = _this$props3.draggingAboveHalf;
      var propsForDnDZone = {
        draggingOver: draggingOver,
        draggingAboveHalf: draggingAboveHalf
      };
      return _react.default.createElement("div", null, _react.default.createElement(_DragAndDropZone.default, Object.assign({}, propsForDnDZone, {
        location: "above"
      })), connectDragPreview(_this.renderForm()), _react.default.createElement(_DragAndDropZone.default, Object.assign({}, propsForDnDZone, {
        location: "below"
      })));
    };

    return _this;
  }

  (0, _createClass2.default)(QuizEntryEdit, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.props.onEditQuizEntryToggle(this.props.quizEntry.id);
    }
  }, {
    key: "componentWillMount",
    value: function componentWillMount() {
      this.props.setUi(_constants.SHOULD_CLONE_ITEM, false);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.props.setUi(_constants.SHOULD_CLONE_ITEM, false);
    }
  }, {
    key: "clickedOutside",
    value: function clickedOutside() {
      setTimeout(this.onSubmit);
    }
  }, {
    key: "ignoreClickOutsideIf",
    value: function ignoreClickOutsideIf(e) {
      var clickingAddContent = document.activeElement.parentNode.className.includes(_constants.ADD_CONTENT_POPOVER_KEY); // Need to iterate over the appNodes since Gauge and lti have a different index for the sdk node

      var appNodes = (0, _ElementsForSelectors.default)(this.props.appContainer); // popovers are rendered "outside" the app (but we don't want to consider the AddContentPopover as such)

      var outsideApp = !this.props.addContentPopoverOpen && appNodes.every(function (node) {
        return node && !node.contains(e.target);
      });
      return this.props.isOccluded || clickingAddContent || outsideApp;
    }
  }, {
    key: "isValid",
    value: function isValid() {
      return this.props.workingEntry.isValid() && this.props.workingQuizEntry.isValid();
    }
  }, {
    key: "renderFooter",
    value: function renderFooter() {
      var isItemOrBankEntry = this.props.quizEntry.isItem || this.props.quizEntry.isBankEntry;
      if (!(isItemOrBankEntry || this.props.disabledForRegrade)) return;
      var footerProps = (0, _pick.default)(this.props, ['alternativeRightFooter', 'changeQuizEntryPoints', 'clearTemporaryItem', 'displayPosition', 'entry', 'guid', 'initialFocusId', 'openModal', 'quizEntry', 'setUi', 'shouldClone', 'workingQuizEntry']);
      return _react.default.createElement(_Footer.default, Object.assign({
        clearChanges: this.clearChanges,
        isValid: this.isValid(),
        successfulSubmit: this.successfulSubmit,
        disableSubmit: !this.state.canSubmit
      }, footerProps));
    }
  }, {
    key: "renderAddToBankModal",
    value: function renderAddToBankModal() {
      if (!this.props.quizEntry.isItem) return;
      return _react.default.createElement(_AddToBankModal.default, {
        label: "Dodaj do banku element\xF3w",
        onContinue: this.handleAddToBankContinue,
        onAdd: this.handleAddToBank,
        getEntry: this.getEntryForBank,
        entryId: this.props.guid,
        entryType: this.props.quizEntry.entryType
      });
    }
  }, {
    key: "renderHeader",
    value: function renderHeader() {
      var headerProps = (0, _pick.default)(this.props, ['changeItemTitle', 'clearModifications', 'clearTemporaryItem', 'connectDragSource', 'disabledForRegrade', 'displayPosition', 'entry', 'guid', 'hideError', 'initialFocusId', 'name', 'quizEntries', 'quizEntry', 'quizId', 'removeQuizEntry', 'setUi', 'shouldClone', 'withConfirm', 'workingEntry']);
      return _react.default.createElement(_Header.default, headerProps);
    }
  }, {
    key: "renderForm",
    value: function renderForm() {
      return _react.default.createElement("div", {
        className: styles.quizEntryEdit,
        "data-automation": "sdk-quiz-entry-edit-div"
      }, _react.default.createElement("div", {
        role: "form"
      }, this.renderHeader(), this.props.children, this.renderFooter()), this.renderAddToBankModal());
    }
  }, {
    key: "render",
    value: function render() {
      return this.props.disabledForRegrade ? this.renderForm() : this.renderDraggable();
    }
  }]);
  QuizEntryEdit.displayName = "QuizEntryEdit";
  return QuizEntryEdit;
}(_react.Component), _class2.propTypes = {
  children: _propTypes.default.oneOfType([_propTypes.default.arrayOf(_propTypes.default.node), _propTypes.default.node]),
  clearModifications: _propTypes.default.func.isRequired,
  // from connected component
  clearNextQuizEntry: _propTypes.default.func.isRequired,
  // from connected component
  clearTemporaryItem: _propTypes.default.func.isRequired,
  // from connected component
  cloneQuizEntry: _propTypes.default.func.isRequired,
  // from connected component
  connectDragPreview: _propTypes.default.func.isRequired,
  // inserted from React DnD
  connectDragSource: _propTypes.default.func.isRequired,
  // inserted from React DnD
  createItem: _propTypes.default.func.isRequired,
  // from connected component
  createTempItem: _propTypes.default.func.isRequired,
  // from connected component
  createTempStimulus: _propTypes.default.func.isRequired,
  // from connected component
  createQuizEntry: _propTypes.default.func.isRequired,
  // from connected component
  disabledForRegrade: _propTypes.default.bool,
  draggingAboveHalf: _propTypes.default.bool.isRequired,
  draggingOver: _propTypes.default.bool.isRequired,
  entry: _reactImmutableProptypes.default.record.isRequired,
  guid: _propTypes.default.string.isRequired,
  addContentPopoverOpen: _propTypes.default.bool.isRequired,
  isOccluded: _propTypes.default.bool,
  nextQuizEntry: _reactImmutableProptypes.default.map,
  openRegradeModal: _propTypes.default.func.isRequired,
  quizEntries: _reactImmutableProptypes.default.listOf(_reactImmutableProptypes.default.record).isRequired,
  quizEntry: _reactImmutableProptypes.default.record.isRequired,
  quizId: _propTypes.default.string.isRequired,
  screenreaderNotification: _propTypes.default.func.isRequired,
  // from connected component
  setUi: _propTypes.default.func.isRequired,
  shouldClone: _propTypes.default.bool,
  showError: _propTypes.default.func.isRequired,
  // from connected component
  switchOffEditing: _propTypes.default.func.isRequired,
  updateQuizEntry: _propTypes.default.func.isRequired,
  // from connected component
  updateItem: _propTypes.default.func.isRequired,
  // from connected component
  workingEntry: _reactImmutableProptypes.default.record.isRequired,
  workingQuizEntry: _reactImmutableProptypes.default.record.isRequired,
  appContainer: _CustomPropTypes.default.selectors.isRequired,
  alternativeRightFooter: _propTypes.default.func,
  changeItemTitle: _propTypes.default.func.isRequired,
  // from connected component
  changeQuizEntryPoints: _propTypes.default.func.isRequired,
  // from connected component
  displayPosition: _propTypes.default.number.isRequired,
  hideError: _propTypes.default.func.isRequired,
  // from connected component
  name: _propTypes.default.string,
  openModal: _propTypes.default.func.isRequired,
  removeQuizEntry: _propTypes.default.func.isRequired,
  // from connected component
  withConfirm: _propTypes.default.func.isRequired,
  initialFocusId: _propTypes.default.string,
  onEditQuizEntryToggle: _propTypes.default.func
}, _class2.defaultProps = {
  alternativeRightFooter: null,
  children: null,
  disabledForRegrade: false,
  name: null,
  nextQuizEntry: null,
  shouldClone: false,
  initialFocusId: null,
  isOccluded: false,
  onEditQuizEntryToggle: function onEditQuizEntryToggle() {}
}, _temp)) || _class);
var UndecoratedQuizEntryEdit = QuizEntryEdit;
exports.UndecoratedQuizEntryEdit = UndecoratedQuizEntryEdit;
var QuizEntryEditRaw = (0, _componentWithOutsideClick.default)(QuizEntryEdit);
exports.QuizEntryEditRaw = QuizEntryEditRaw;

var _default = (0, _reactDnd.DragSource)(_dragAndDropUtils.ItemTypes.QUIZ_ENTRY, _dragAndDropUtils.dragSource, _dragAndDropUtils.collectDrag)(QuizEntryEditRaw);

exports.default = _default;