'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.StimulusEdit = 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 _dec, _class, _class2, _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 _first = require('lodash/first');

var _first2 = _interopRequireDefault(_first);

var _partial = require('lodash/partial');

var _partial2 = _interopRequireDefault(_partial);

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

var _Button2 = _interopRequireDefault(_Button);

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

var _ToggleDetails2 = _interopRequireDefault(_ToggleDetails);

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

var _lib2 = _interopRequireDefault(_lib);

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

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

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

var _AddToBankModal2 = _interopRequireDefault(_AddToBankModal);

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

var _AddToBankOptions2 = _interopRequireDefault(_AddToBankOptions);

var _WarningWrapper = require('../../WarningWrapper');

var _WarningWrapper2 = _interopRequireDefault(_WarningWrapper);

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

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

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

var _ElementsForSelectors2 = _interopRequireDefault(_ElementsForSelectors);

var _StimulusShowInfo = require('../StimulusShowInfo');

var _StimulusShowInfo2 = _interopRequireDefault(_StimulusShowInfo);

var _StimulusEditInfo = require('../StimulusEditInfo');

var _StimulusEditInfo2 = _interopRequireDefault(_StimulusEditInfo);

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

var _componentWithOutsideClick2 = _interopRequireDefault(_componentWithOutsideClick);

var _index = require('../../../../../building/components/resources/ActionButtons/index');

var _index2 = _interopRequireDefault(_index);

var _IfFeature = require('../../../shared/IfFeature');

var _IfFeature2 = _interopRequireDefault(_IfFeature);

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n.StimulusEdit__styles__stimulus {\n  padding-top: ' + theme.stimulusPadding + ';\n  padding-bottom: ' + theme.stimulusPadding + ';\n}\n\n.StimulusEdit__styles__footer {\n  display: flex;\n  justify-content: flex-end;\n}\n\n.StimulusEdit__styles__buttonWrapper {\n  padding-left: ' + theme.buttonWrapperPadding + ';\n}\n\n.StimulusEdit__styles__header {\n  height: 1rem;\n  padding-left: ' + theme.headerPadding + ';\n  padding-right: ' + theme.headerPadding + ';\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n}\n\n.StimulusEdit__styles__stimulusContent {\n  height: 100%;\n  padding: ' + theme.stimulusContentPadding + ';\n}\n\n.StimulusEdit__styles__stimulusLabel {\n  color: ' + theme.stimulusLabelColor + ';\n  font-size: ' + theme.stimulusLabelFontSize + ';\n}\n\n.StimulusEdit__styles__stimulusButtons {\n  flex: 0 0 auto;\n  display: inline-flex;\n  text-align: right;\n  z-index: ' + theme.stimulusButtonsZIndex + ';\n  color: ' + theme.stimulusButtonsColor + ';\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: ' + theme.optionPadding + ';\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 = exports.StimulusEdit = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(StimulusEdit, _Component);

  function StimulusEdit() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = StimulusEdit.__proto__ || Object.getPrototypeOf(StimulusEdit)).call.apply(_ref, [this].concat(args))), _this), _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 = function (stimulusData) {
      var _this$props = _this.props,
          quizId = _this$props.quizId,
          quizEntry = _this$props.quizEntry;

      var mods = Object.assign({}, quizEntry.toJS(), {
        entryId: stimulusData.id,
        entryType: 'Stimulus'
      });
      _this.props.updateQuizEntry(quizId, quizEntry.id, mods).then(function () {
        _this.props.getQuizEntries(quizId);
        _this.afterSubmit();
      });
    }, _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, _first2.default)(interactionTypeData.scoringAlgorithmOptions),
          scoringData: scoringData,
          userResponseType: (0, _first2.default)(interactionTypeData.userResponseTypeOptions)
        }, parentEntryId, stimulusId);
      }

      _this.props.clearNextQuizEntry();
    }, _this.onSubmit = function (e) {
      var _this$props2 = _this.props,
          stimulus = _this$props2.stimulus,
          workingStimulus = _this$props2.workingStimulus,
          quizId = _this$props2.quizId,
          quizEntry = _this$props2.quizEntry;


      if (!workingStimulus.isValid()) {
        _this.props.showError(_this.props.guid);
        _this.props.screenreaderNotification('Stimolo non salvato a causa di errori di convalida con i dati.');
        _this.props.clearNextQuizEntry();
        return;
      }

      _this.setState({ canSubmit: false });
      _this.props.hideError(_this.props.guid);

      if (stimulus.isTemporary()) {
        _this.props.createStimulusAndQuizEntry(quizId, workingStimulus.toJS(), quizEntry).then(function () {
          _this.props.clearTemporaryStimulus(quizId);
          _this.afterSubmit();
        });
        return;
      }

      if (_this.props.shouldClone) {
        _this.props.createStimulus(workingStimulus, _this.props.quizId, 'quiz', workingStimulus.id).then(_this.handleStimulusCreated);
        _this.props.clearTemporaryStimulus(quizId);
        return;
      }
      _this.props.updateStimulus(workingStimulus.toJS(), quizId).then(function () {
        _this.afterSubmit();
      });
    }, _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;
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.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, _ElementsForSelectors2.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('Modifiche allo stimolo salvate.');
      if (this.props.nextQuizEntry) {
        this.createNextQuizEntry();
      }
    }
  }, {
    key: 'saveText',
    value: function saveText() {
      return this.props.stimulus.isTemporary() ? 'Aggiungi stimolo' : 'Salva stimolo';
    }
  }, {
    key: 'renderAddToBankModal',
    value: function renderAddToBankModal() {
      return _react2.default.createElement(_AddToBankModal2.default, {
        label: 'Aggiungi a una banca di elementi',
        onAdd: this.handleAddToBank,
        onContinue: this.handleAddToBankContinue,
        getEntry: this.getEntryForBank,
        entryId: this.props.guid,
        entryType: this.props.quizEntry.entryType
      });
    }
  }, {
    key: 'renderAddToBankOptions',
    value: function renderAddToBankOptions() {
      return _react2.default.createElement(
        _IfFeature2.default,
        { name: 'stimulus_banking' },
        _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            _ToggleDetails2.default,
            { variant: 'filled', key: 'itemBanking', summary: 'Banca elementi' },
            _react2.default.createElement(
              'div',
              { className: styles.optionWrapper },
              _react2.default.createElement(_AddToBankOptions2.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 _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { className: styles.stimulus },
          _react2.default.createElement(
            'div',
            { className: styles.header },
            _react2.default.createElement(
              'div',
              { className: styles.stimulusLabel },
              'Stimolo'
            ),
            _react2.default.createElement(_index2.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
            })
          ),
          _react2.default.createElement(
            'div',
            { className: styles.stimulusContent },
            _react2.default.createElement(_StimulusEditInfo2.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()
          )
        ),
        _react2.default.createElement(
          'div',
          { className: styles.footer },
          _react2.default.createElement(
            'div',
            { className: styles.buttonWrapper },
            _react2.default.createElement(
              _Button2.default,
              {
                type: 'button',
                onClick: this.onCancel,
                'data-automation': 'sdk-stimulus-discardButton'
              },
              'Ignora'
            )
          ),
          _react2.default.createElement(
            'div',
            { className: styles.buttonWrapper },
            _react2.default.createElement(
              _Button2.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 _react2.default.createElement(
          _WarningWrapper2.default,
          this.props.bankEntryWarningWrapperProps(),
          _react2.default.createElement(_StimulusShowInfo2.default, this.props)
        );
      }

      var _props = this.props,
          stimulus = _props.stimulus,
          quizEntry = _props.quizEntry;

      var propForWrapperFunc = quizEntry.isArchivedBankEntry ? _warningHelpers.propsForBankEntryVersioningWrapper : _warningHelpers.propsForStimulusVersioningWrapper;
      var propsForStimulusVersioning = propForWrapperFunc(stimulus.isImmutable() || quizEntry.isArchivedBankEntry, this.props.shouldClone, (0, _partial2.default)(this.props.setUi, _constants.SHOULD_CLONE_ITEM), this.props.switchOffEditing, true, quizEntry.isArchivedBankEntry ? 'info' : 'warning');

      return _react2.default.createElement(
        _WarningWrapper2.default,
        propsForStimulusVersioning,
        this.renderStimulusEdit()
      );
    }
  }]);
  StimulusEdit.displayName = 'StimulusEdit'
  ;
  return StimulusEdit;
}(_react.Component), _class2.propTypes = {
  addContentPopoverOpen: _propTypes2.default.bool.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  bankEntryWarningWrapperProps: _propTypes2.default.func,
  clearModifications: _propTypes2.default.func.isRequired,
  clearNextQuizEntry: _propTypes2.default.func.isRequired,
  createTempItem: _propTypes2.default.func.isRequired,
  createTempStimulus: _propTypes2.default.func.isRequired,
  clearTemporaryStimulus: _propTypes2.default.func.isRequired,
  createQuizEntry: _propTypes2.default.func.isRequired,
  connectDragSource: _propTypes2.default.func.isRequired,
  createStimulus: _propTypes2.default.func.isRequired,
  createStimulusAndQuizEntry: _propTypes2.default.func.isRequired,
  displayPosition: _propTypes2.default.number.isRequired,
  errorsShowing: _propTypes2.default.bool,
  getQuizEntries: _propTypes2.default.func.isRequired,
  guid: _propTypes2.default.string.isRequired,
  hideError: _propTypes2.default.func.isRequired,
  isBankedContent: _propTypes2.default.bool,
  openModal: _propTypes2.default.string.isRequired,
  openDeleteStimulusModal: _propTypes2.default.func.isRequired,
  nextQuizEntry: _reactImmutableProptypes2.default.map.isRequired,
  quizEntries: _reactImmutableProptypes2.default.listOf(_reactImmutableProptypes2.default.record).isRequired,
  quizEntry: _reactImmutableProptypes2.default.record.isRequired,
  quizId: _propTypes2.default.string.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  setUi: _propTypes2.default.func.isRequired,
  setUploadStatus: _propTypes2.default.func.isRequired,
  shouldClone: _propTypes2.default.bool.isRequired,
  showError: _propTypes2.default.func.isRequired,
  stimulus: _reactImmutableProptypes2.default.record.isRequired,
  switchOnEditing: _propTypes2.default.func.isRequired,
  switchOffEditing: _propTypes2.default.func.isRequired,
  updateQuizEntry: _propTypes2.default.func.isRequired,
  updateStimulus: _propTypes2.default.func.isRequired,
  workingQuizEntry: _reactImmutableProptypes2.default.record.isRequired,
  workingStimulus: _reactImmutableProptypes2.default.record.isRequired,
  onEditToggle: _propTypes2.default.func.isRequired,
  shouldFocusOnMount: _propTypes2.default.func.isRequired
}, _class2.defaultProps = {
  bankEntryWarningWrapperProps: function bankEntryWarningWrapperProps() {},
  errorsShowing: true,
  isBankedContent: false
}, _temp2)) || _class);
exports.default = (0, _componentWithOutsideClick2.default)(StimulusEdit);