"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.StimulusEdit = 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 _first = _interopRequireDefault(require("lodash/first"));

var _partial = _interopRequireDefault(require("lodash/partial"));

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

var _ToggleDetails = _interopRequireDefault(require("@instructure/ui-toggle-details/lib/components/ToggleDetails"));

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

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

var _warningHelpers = require("../../../../util/warningHelpers");

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

var _AddToBankOptions = _interopRequireDefault(require("../../../../../building/components/resources/AddToBankOptions"));

var _WarningWrapper = _interopRequireDefault(require("../../WarningWrapper"));

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

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

var _StimulusShowInfo = _interopRequireDefault(require("../StimulusShowInfo"));

var _StimulusEditInfo = _interopRequireDefault(require("../StimulusEditInfo"));

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

var _ActionButtons = _interopRequireDefault(require("../../../../../building/components/resources/ActionButtons"));

var _IfFeature = _interopRequireDefault(require("../../../shared/IfFeature"));

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

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

var _dec, _class, _class2, _temp;

var styles = {
  componentId: 'eCUGW',
  template: function template(theme) {
    return "\n\n.StimulusEdit__styles__stimulus {\n  padding-top: ".concat(theme.stimulusPadding || 'inherit', ";\n  padding-bottom: ").concat(theme.stimulusPadding || 'inherit', ";\n}\n\n.StimulusEdit__styles__footer {\n  display: flex;\n  justify-content: flex-end;\n}\n\n.StimulusEdit__styles__buttonWrapper {\n  padding-left: ").concat(theme.buttonWrapperPadding || 'inherit', ";\n}\n\n.StimulusEdit__styles__header {\n  height: 1rem;\n  padding-left: ").concat(theme.headerPadding || 'inherit', ";\n  padding-right: ").concat(theme.headerPadding || 'inherit', ";\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n}\n\n.StimulusEdit__styles__stimulusContent {\n  height: 100%;\n  padding: ").concat(theme.stimulusContentPadding || 'inherit', ";\n}\n\n.StimulusEdit__styles__stimulusLabel {\n  color: ").concat(theme.stimulusLabelColor || 'inherit', ";\n  font-size: ").concat(theme.stimulusLabelFontSize || 'inherit', ";\n}\n\n.StimulusEdit__styles__stimulusButtons {\n  flex: 0 0 auto;\n  display: inline-flex;\n  text-align: right;\n  z-index: ").concat(theme.stimulusButtonsZIndex || 'inherit', ";\n  color: ").concat(theme.stimulusButtonsColor || 'inherit', ";\n}\n\n[dir=\"ltr\"] .StimulusEdit__styles__stimulusButtons {\n  text-align: right;\n}\n\n[dir=\"rtl\"] .StimulusEdit__styles__stimulusButtons {\n  text-align: right;\n}\n\n.StimulusEdit__styles__stimulusButtons button {\n  background-color: transparent;\n  background-color: initial;\n}\n\n.StimulusEdit__styles__optionWrapper {\n  padding-top: ").concat(theme.optionPadding || 'inherit', ";\n}\n");
  },
  'stimulus': 'StimulusEdit__styles__stimulus',
  'footer': 'StimulusEdit__styles__footer',
  'buttonWrapper': 'StimulusEdit__styles__buttonWrapper',
  'header': 'StimulusEdit__styles__header',
  'stimulusContent': 'StimulusEdit__styles__stimulusContent',
  'stimulusLabel': 'StimulusEdit__styles__stimulusLabel',
  'stimulusButtons': 'StimulusEdit__styles__stimulusButtons',
  'optionWrapper': 'StimulusEdit__styles__optionWrapper'
};
var StimulusEdit = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(StimulusEdit, _Component);

  function StimulusEdit() {
    var _getPrototypeOf2;

    var _this;

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

    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)(StimulusEdit)).call.apply(_getPrototypeOf2, [this].concat(args)));
    _this.state = {
      canSubmit: true
    };

    _this.clearModifications = function () {
      _this.props.clearModifications('stimuli', _this.props.stimulus.id);
    };

    _this.onCancel = function (e) {
      _this.props.hideError(_this.props.guid);

      if (_this.props.stimulus.isTemporary()) {
        _this.props.clearTemporaryStimulus(_this.props.quizId);
      }

      _this.props.switchOffEditing();

      _this.clearModifications();

      _this.props.setUi(_constants.SHOULD_CLONE_ITEM, false);
    };

    _this.handleDeleteStimulus = function () {
      if (_this.props.stimulus.isTemporary()) {
        _this.onCancel();

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

    _this.handleStimulusCreated =
    /*#__PURE__*/
    function () {
      var _ref = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee(stimulusData) {
        var _this$props, quizId, quizEntry, mods;

        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$props = _this.props, quizId = _this$props.quizId, quizEntry = _this$props.quizEntry;
                mods = Object.assign({}, quizEntry.toJS(), {
                  entryId: stimulusData.id,
                  entryType: 'Stimulus'
                });
                _context.next = 4;
                return _this.props.updateQuizEntry(quizId, quizEntry.id, mods);

              case 4:
                _this.props.getQuizEntries(quizId);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }();

    _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.onSubmit =
    /*#__PURE__*/
    function () {
      var _ref2 = (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee2(e) {
        var _this$props2, stimulus, workingStimulus, quizId, quizEntry, stimulusData;

        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$props2 = _this.props, stimulus = _this$props2.stimulus, workingStimulus = _this$props2.workingStimulus, quizId = _this$props2.quizId, quizEntry = _this$props2.quizEntry;

                if (workingStimulus.isValid()) {
                  _context2.next = 6;
                  break;
                }

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

                _this.props.screenreaderNotification("Hvatning ekki vistu\xF0 vegna fullgildingarvillna \xED g\xF6gnum.");

                _this.props.clearNextQuizEntry();

                return _context2.abrupt("return");

              case 6:
                _this.setState({
                  canSubmit: false
                });

                _this.props.hideError(_this.props.guid);

                _context2.prev = 8;

                if (!stimulus.isTemporary()) {
                  _context2.next = 15;
                  break;
                }

                _context2.next = 12;
                return _this.props.createStimulusAndQuizEntry(quizId, workingStimulus.toJS(), quizEntry);

              case 12:
                _this.props.clearTemporaryStimulus(quizId);

                _context2.next = 26;
                break;

              case 15:
                if (!_this.props.shouldClone) {
                  _context2.next = 24;
                  break;
                }

                _context2.next = 18;
                return _this.props.createStimulus(workingStimulus, _this.props.quizId, 'quiz', workingStimulus.id);

              case 18:
                stimulusData = _context2.sent;
                _context2.next = 21;
                return _this.handleStimulusCreated(stimulusData);

              case 21:
                _this.props.clearTemporaryStimulus(quizId);

                _context2.next = 26;
                break;

              case 24:
                _context2.next = 26;
                return _this.props.updateStimulus(workingStimulus.toJS(), quizId);

              case 26:
                _context2.next = 32;
                break;

              case 28:
                _context2.prev = 28;
                _context2.t0 = _context2["catch"](8);

                _this.setState({
                  canSubmit: true
                });

                throw _context2.t0;

              case 32:
                _this.afterSubmit();

              case 33:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, null, [[8, 28]]);
      }));

      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }();

    _this.onSuccess = function (url) {
      _this.props.setUploadStatus(_constants.FILE_UPLOAD_SUCCESS);
    };

    _this.handleAddToBankContinue = function () {
      _this.setState({
        canSubmit: false
      });
    };

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

        _this.props.clearTemporaryStimulus(_this.props.quizId);

        _this.clearModifications();

        _this.props.switchOffEditing();
      } else {
        _this.props.updateQuizEntry(_this.props.quizId, _this.props.workingQuizEntry.id, {
          entryId: bankEntry.id,
          entryType: 'BankEntry'
        });
      }
    };

    _this.getEntryForBank = function () {
      var _this$props3 = _this.props,
          stimulus = _this$props3.stimulus,
          workingStimulus = _this$props3.workingStimulus,
          quizId = _this$props3.quizId,
          shouldClone = _this$props3.shouldClone;

      if (stimulus.isTemporary()) {
        return _this.props.createStimulus(workingStimulus, quizId);
      } else if (stimulus.hasModifications()) {
        if (shouldClone) {
          return _this.props.createStimulus(workingStimulus, quizId);
        } else {
          return _this.props.updateStimulus(workingStimulus, quizId);
        }
      } else {
        return Promise.resolve(stimulus);
      }
    };

    _this.setTitleRef = function (elem) {
      _this.stimulusEditTitleRef = elem;
    };

    return _this;
  }

  (0, _createClass2.default)(StimulusEdit, [{
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      if (!this.props.nextQuizEntry) {
        // adding timeout so any content rce events
        // fire before the mods are cleared
        setTimeout(this.clearModifications);
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      this.stimulusEditTitleRef && this.stimulusEditTitleRef.focus();
      this.props.switchOnEditing();
      this.props.onEditToggle(this.props.quizEntry.id);
    }
  }, {
    key: "clickedOutside",
    value: function clickedOutside() {
      if (this.props.stimulus.isImmutable() || this.props.isBankedContent) {
        this.props.switchOffEditing();
      } else {
        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 clickingAddContent || outsideApp;
    }
  }, {
    key: "afterSubmit",
    value: function afterSubmit() {
      this.props.switchOffEditing();
      this.clearModifications();
      this.props.setUi(_constants.SHOULD_CLONE_ITEM, false);
      this.props.screenreaderNotification("Breytingar \xE1 hvatningu vista\xF0ar.");

      if (this.props.nextQuizEntry) {
        this.createNextQuizEntry();
      }
    }
  }, {
    key: "saveText",
    value: function saveText() {
      return this.props.stimulus.isTemporary() ? "B\xE6ta vi\xF0 hvatningu" : "Vista hvatningu";
    }
  }, {
    key: "renderAddToBankModal",
    value: function renderAddToBankModal() {
      return _react.default.createElement(_AddToBankModal.default, {
        label: "B\xE6ta vi\xF0 atri\xF0abanka",
        onAdd: this.handleAddToBank,
        onContinue: this.handleAddToBankContinue,
        getEntry: this.getEntryForBank,
        entryId: this.props.guid,
        entryType: this.props.quizEntry.entryType
      });
    }
  }, {
    key: "renderAddToBankOptions",
    value: function renderAddToBankOptions() {
      return _react.default.createElement(_IfFeature.default, {
        name: "stimulus_banking"
      }, _react.default.createElement("div", null, _react.default.createElement(_ToggleDetails.default, {
        variant: "filled",
        key: "itemBanking",
        summary: "Sett \xED atri\xF0abanka"
      }, _react.default.createElement("div", {
        className: styles.optionWrapper
      }, _react.default.createElement(_AddToBankOptions.default, {
        displayPosition: this.props.displayPosition,
        entryType: this.props.quizEntry.entryType,
        guid: this.props.guid,
        isValid: this.props.workingStimulus.isValid(),
        openModal: this.props.openModal,
        screenreaderNotification: this.props.screenreaderNotification,
        showError: this.props.showError
      }))), this.renderAddToBankModal()));
    }
  }, {
    key: "renderStimulusEdit",
    value: function renderStimulusEdit() {
      return _react.default.createElement("div", null, _react.default.createElement("div", {
        className: styles.stimulus
      }, _react.default.createElement("div", {
        className: styles.header
      }, _react.default.createElement("div", {
        className: styles.stimulusLabel
      }, "Hvatning"), _react.default.createElement(_ActionButtons.default, {
        connectDragSource: this.props.connectDragSource,
        displayPosition: this.props.displayPosition,
        onDelete: this.handleDeleteStimulus,
        quizEntries: this.props.quizEntries,
        quizEntry: this.props.quizEntry,
        shouldDisableDragHandle: true,
        shouldRenderEdit: false,
        shouldFocusOnMount: this.props.shouldFocusOnMount
      })), _react.default.createElement("div", {
        className: styles.stimulusContent
      }, _react.default.createElement(_StimulusEditInfo.default, {
        errorsShowing: this.props.errorsShowing,
        guid: this.props.guid,
        stimulus: this.props.stimulus,
        isBankedContent: this.props.isBankedContent,
        parentId: this.props.quizId,
        parentType: "quiz",
        setTitleRef: this.setTitleRef
      }), this.renderAddToBankOptions())), _react.default.createElement("div", {
        className: styles.footer
      }, _react.default.createElement("div", {
        className: styles.buttonWrapper
      }, _react.default.createElement(_Button.default, {
        type: "button",
        onClick: this.onCancel,
        "data-automation": "sdk-stimulus-discardButton"
      }, "Henda")), _react.default.createElement("div", {
        className: styles.buttonWrapper
      }, _react.default.createElement(_Button.default, {
        type: "button",
        variant: "primary",
        disabled: !this.state.canSubmit,
        onClick: this.onSubmit
      }, this.saveText()))));
    }
  }, {
    key: "render",
    value: function render() {
      this.stimulusEditInfoRef = null;

      if (this.props.isBankedContent) {
        return _react.default.createElement(_WarningWrapper.default, this.props.bankEntryWarningWrapperProps(), _react.default.createElement(_StimulusShowInfo.default, this.props));
      }

      var _this$props4 = this.props,
          stimulus = _this$props4.stimulus,
          quizEntry = _this$props4.quizEntry;
      var propForWrapperFunc = quizEntry.isArchivedBankEntry ? _warningHelpers.propsForBankEntryVersioningWrapper : _warningHelpers.propsForStimulusVersioningWrapper;
      var propsForStimulusVersioning = propForWrapperFunc(stimulus.isImmutable() || quizEntry.isArchivedBankEntry, this.props.shouldClone, (0, _partial.default)(this.props.setUi, _constants.SHOULD_CLONE_ITEM), this.props.switchOffEditing, true, quizEntry.isArchivedBankEntry ? 'info' : 'warning');
      return _react.default.createElement(_WarningWrapper.default, propsForStimulusVersioning, this.renderStimulusEdit());
    }
  }]);
  StimulusEdit.displayName = "StimulusEdit";
  return StimulusEdit;
}(_react.Component), _class2.propTypes = {
  addContentPopoverOpen: _propTypes.default.bool.isRequired,
  appContainer: _CustomPropTypes.default.selectors.isRequired,
  bankEntryWarningWrapperProps: _propTypes.default.func,
  clearModifications: _propTypes.default.func.isRequired,
  clearNextQuizEntry: _propTypes.default.func.isRequired,
  createTempItem: _propTypes.default.func.isRequired,
  createTempStimulus: _propTypes.default.func.isRequired,
  clearTemporaryStimulus: _propTypes.default.func.isRequired,
  createQuizEntry: _propTypes.default.func.isRequired,
  connectDragSource: _propTypes.default.func.isRequired,
  createStimulus: _propTypes.default.func.isRequired,
  createStimulusAndQuizEntry: _propTypes.default.func.isRequired,
  displayPosition: _propTypes.default.number.isRequired,
  errorsShowing: _propTypes.default.bool,
  getQuizEntries: _propTypes.default.func.isRequired,
  guid: _propTypes.default.string.isRequired,
  hideError: _propTypes.default.func.isRequired,
  isBankedContent: _propTypes.default.bool,
  openModal: _propTypes.default.string.isRequired,
  openDeleteStimulusModal: _propTypes.default.func.isRequired,
  nextQuizEntry: _reactImmutableProptypes.default.map.isRequired,
  quizEntries: _reactImmutableProptypes.default.listOf(_reactImmutableProptypes.default.record).isRequired,
  quizEntry: _reactImmutableProptypes.default.record.isRequired,
  quizId: _propTypes.default.string.isRequired,
  screenreaderNotification: _propTypes.default.func.isRequired,
  setUi: _propTypes.default.func.isRequired,
  setUploadStatus: _propTypes.default.func.isRequired,
  shouldClone: _propTypes.default.bool.isRequired,
  showError: _propTypes.default.func.isRequired,
  stimulus: _reactImmutableProptypes.default.record.isRequired,
  switchOnEditing: _propTypes.default.func.isRequired,
  switchOffEditing: _propTypes.default.func.isRequired,
  updateQuizEntry: _propTypes.default.func.isRequired,
  updateStimulus: _propTypes.default.func.isRequired,
  workingQuizEntry: _reactImmutableProptypes.default.record.isRequired,
  workingStimulus: _reactImmutableProptypes.default.record.isRequired,
  onEditToggle: _propTypes.default.func.isRequired,
  shouldFocusOnMount: _propTypes.default.func.isRequired
}, _class2.defaultProps = {
  bankEntryWarningWrapperProps: function bankEntryWarningWrapperProps() {},
  errorsShowing: true,
  isBankedContent: false
}, _temp)) || _class);
exports.StimulusEdit = StimulusEdit;

var _default = (0, _componentWithOutsideClick.default)(StimulusEdit);

exports.default = _default;