'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.QuizEntryEditRaw = exports.UndecoratedQuizEntryEdit = 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,
    _default_frCA_number = Intl.NumberFormat('fr-CA', { style: 'decimal' }).format;

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 _reactDnd = require('react-dnd');

var _pick = require('lodash/pick');

var _pick2 = _interopRequireDefault(_pick);

var _first = require('lodash/first');

var _first2 = _interopRequireDefault(_first);

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

var _lib2 = _interopRequireDefault(_lib);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

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

var _ElementsForSelectors2 = _interopRequireDefault(_ElementsForSelectors);

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

var _AddToBankModal2 = _interopRequireDefault(_AddToBankModal);

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

var _DragAndDropZone2 = _interopRequireDefault(_DragAndDropZone);

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

var _componentWithOutsideClick2 = _interopRequireDefault(_componentWithOutsideClick);

var _Header = require('./Header');

var _Header2 = _interopRequireDefault(_Header);

var _Footer = require('./Footer');

var _Footer2 = _interopRequireDefault(_Footer);

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

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

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

var _theme2 = _interopRequireDefault(_theme);

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

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n/* WRAPPER */\n\n.QuizEntryEdit__styles__quizEntryEdit {\n  font-size: ' + theme.quizEntryEditFontSize + ';\n  position: relative;\n  transform: translate3d(0, 0, 0); /* for drag and drop preview to work */\n  padding: ' + theme.quizEntryEditPadding + ' 0;\n  z-index: 3333;\n}\n';
  },
  'quizEntryEdit': 'QuizEntryEdit__styles__quizEntryEdit'
};
var QuizEntryEdit = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(QuizEntryEdit, _Component);

  function QuizEntryEdit() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = QuizEntryEdit.__proto__ || Object.getPrototypeOf(QuizEntryEdit)).call.apply(_ref, [this].concat(args))), _this), _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 = '\xC9l\xE9ment ' + _default_frCA_number(displayPosition) + ' ne peut pas \xEAtre enregistr\xE9 \xE0 cause de donn\xE9es d\'entr\xE9e non valides.';
        _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, _first2.default)(interactionTypeData.scoringAlgorithmOptions),
          scoringData: scoringData,
          userResponseType: (0, _first2.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 = function () {
      _this.setState({ canSubmit: false });
      _this.props.hideError(_this.props.guid);
      _this.createOrUpdateItem().then(_this.createOrUpdateQuizEntry).then(function () {
        _this.props.clearTemporaryItem(_this.props.quizId);
        if (_this.props.shouldClone) {
          _this.props.openRegradeModal();
        }
        _this.clearModifications();
        if (_this.props.nextQuizEntry) {
          _this.createNextQuizEntry();
        }
      });
      _this.props.switchOffEditing();
    }, _this.clearChanges = function () {
      _this.clearModifications();
      if (_this.props.quizEntry.isTemporary) {
        _this.props.clearTemporaryItem(_this.props.quizId);
      }
    }, _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.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 _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(_DragAndDropZone2.default, Object.assign({}, propsForDnDZone, { location: 'above' })),
        connectDragPreview(_this.renderForm()),
        _react2.default.createElement(_DragAndDropZone2.default, Object.assign({}, propsForDnDZone, { location: 'below' }))
      );
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.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, _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 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, _pick2.default)(this.props, ['alternativeRightFooter', 'changeQuizEntryPoints', 'clearModifications', 'clearTemporaryItem', 'displayPosition', 'entry', 'guid', 'initialFocusId', 'openModal', 'quizEntry', 'setUi', 'shouldClone', 'workingQuizEntry']);

      return _react2.default.createElement(_Footer2.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 _react2.default.createElement(_AddToBankModal2.default, {
        label: 'Ajouter \xE0 une banque d\'\xE9l\xE9ments',
        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, _pick2.default)(this.props, ['changeItemTitle', 'clearModifications', 'clearTemporaryItem', 'connectDragSource', 'disabledForRegrade', 'displayPosition', 'entry', 'guid', 'hideError', 'initialFocusId', 'name', 'quizEntries', 'quizEntry', 'quizId', 'removeQuizEntry', 'setUi', 'shouldClone', 'withConfirm', 'workingEntry']);

      return _react2.default.createElement(_Header2.default, headerProps);
    }
  }, {
    key: 'renderForm',
    value: function renderForm() {
      return _react2.default.createElement(
        'div',
        { className: styles.quizEntryEdit, 'data-automation': 'sdk-quiz-entry-edit-div' },
        _react2.default.createElement(
          'form',
          null,
          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: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]),
  clearModifications: _propTypes2.default.func.isRequired, // from connected component
  clearNextQuizEntry: _propTypes2.default.func.isRequired, // from connected component
  clearTemporaryItem: _propTypes2.default.func.isRequired, // from connected component
  cloneQuizEntry: _propTypes2.default.func.isRequired, // from connected component
  connectDragPreview: _propTypes2.default.func.isRequired, // inserted from React DnD
  connectDragSource: _propTypes2.default.func.isRequired, // inserted from React DnD
  createItem: _propTypes2.default.func.isRequired, // from connected component
  createTempItem: _propTypes2.default.func.isRequired, // from connected component
  createTempStimulus: _propTypes2.default.func.isRequired, // from connected component
  createQuizEntry: _propTypes2.default.func.isRequired, // from connected component
  disabledForRegrade: _propTypes2.default.bool,
  draggingAboveHalf: _propTypes2.default.bool.isRequired,
  draggingOver: _propTypes2.default.bool.isRequired,
  entry: _reactImmutableProptypes2.default.record.isRequired,
  guid: _propTypes2.default.string.isRequired,
  addContentPopoverOpen: _propTypes2.default.bool.isRequired,
  isOccluded: _propTypes2.default.bool,
  nextQuizEntry: _reactImmutableProptypes2.default.map,
  openRegradeModal: _propTypes2.default.func.isRequired,
  quizEntries: _reactImmutableProptypes2.default.listOf(_reactImmutableProptypes2.default.record).isRequired,
  quizEntry: _reactImmutableProptypes2.default.record.isRequired,
  quizId: _propTypes2.default.string.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired, // from connected component
  setUi: _propTypes2.default.func.isRequired,
  shouldClone: _propTypes2.default.bool,
  showError: _propTypes2.default.func.isRequired, // from connected component
  switchOffEditing: _propTypes2.default.func.isRequired,
  updateQuizEntry: _propTypes2.default.func.isRequired, // from connected component
  updateItem: _propTypes2.default.func.isRequired, // from connected component
  workingEntry: _reactImmutableProptypes2.default.record.isRequired,
  workingQuizEntry: _reactImmutableProptypes2.default.record.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,

  alternativeRightFooter: _propTypes2.default.func,
  changeItemTitle: _propTypes2.default.func.isRequired, // from connected component
  changeQuizEntryPoints: _propTypes2.default.func.isRequired, // from connected component
  displayPosition: _propTypes2.default.number.isRequired,
  hideError: _propTypes2.default.func.isRequired, // from connected component
  name: _propTypes2.default.string,
  openModal: _propTypes2.default.func.isRequired,
  removeQuizEntry: _propTypes2.default.func.isRequired, // from connected component
  withConfirm: _propTypes2.default.func.isRequired,
  initialFocusId: _propTypes2.default.string,
  onEditQuizEntryToggle: _propTypes2.default.func
}, _class2.defaultProps = {
  alternativeRightFooter: null,
  children: null,
  disabledForRegrade: false,
  name: null,
  nextQuizEntry: null,
  shouldClone: false,
  initialFocusId: null,
  isOccluded: false,
  onEditQuizEntryToggle: function onEditQuizEntryToggle() {}
}, _temp2)) || _class);
var UndecoratedQuizEntryEdit = exports.UndecoratedQuizEntryEdit = QuizEntryEdit;

var QuizEntryEditRaw = exports.QuizEntryEditRaw = (0, _componentWithOutsideClick2.default)(QuizEntryEdit);

exports.default = (0, _reactDnd.DragSource)(_dragAndDropUtils.ItemTypes.QUIZ_ENTRY, _dragAndDropUtils.dragSource, _dragAndDropUtils.collectDrag)(QuizEntryEditRaw);