'use strict';

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

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

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 _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

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

var _partial2 = _interopRequireDefault(_partial);

var _Alert = require('@instructure/ui-alerts/lib/components/Alert');

var _Alert2 = _interopRequireDefault(_Alert);

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

var _Button2 = _interopRequireDefault(_Button);

var _Overlay = require('@instructure/ui-overlays/lib/components/Overlay');

var _Overlay2 = _interopRequireDefault(_Overlay);

var _Mask = require('@instructure/ui-overlays/lib/components/Mask');

var _Mask2 = _interopRequireDefault(_Mask);

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

var _lib2 = _interopRequireDefault(_lib);

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

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

var _TimerService = require('../../../../common/util/TimerService');

var _TimerService2 = _interopRequireDefault(_TimerService);

var _TimeRecordingService = require('../../../../common/util/TimeRecordingService');

var _TimeRecordingService2 = _interopRequireDefault(_TimeRecordingService);

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

var _ElementsForSelectors2 = _interopRequireDefault(_ElementsForSelectors);

var _Card = require('../../../../common/components/shared/Card');

var _Card2 = _interopRequireDefault(_Card);

var _Page = require('../../../../common/components/layout/Page');

var _Page2 = _interopRequireDefault(_Page);

var _Spinner = require('../../../../common/components/shared/spinner/Spinner');

var _Spinner2 = _interopRequireDefault(_Spinner);

var _TakeBody = require('./TakeBody');

var _TakeBody2 = _interopRequireDefault(_TakeBody);

var _TakeFooter = require('./TakeFooter');

var _TakeFooter2 = _interopRequireDefault(_TakeFooter);

var _TakeHeader = require('./TakeHeader');

var _TakeHeader2 = _interopRequireDefault(_TakeHeader);

var _Sidebar = require('../../layout/Sidebar');

var _Sidebar2 = _interopRequireDefault(_Sidebar);

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.Take__styles__root {\n  display: flex;\n  flex-direction: column;\n  box-sizing: border-box;\n  margin: ' + theme.rootMargin + ' auto;\n  max-width: ' + theme.rootMaxWidth + ';\n}\n\n.Take__styles__body {\n  margin-top: ' + theme.bodyMargin + ';\n  margin-left: 0;\n  margin-right: 0;\n}\n\n.Take__styles__overlayBody {\n  display: flex;\n  flex-direction: column;\n\n  align-items: center;\n  justify-content: center;\n\n  height: 100vh;\n}\n\n.Take__styles__overlayItem {\n  vertical-align: baseline;\n}\n';
  },
  'root': 'Take__styles__root',
  'body': 'Take__styles__body',
  'overlayBody': 'Take__styles__overlayBody',
  'overlayItem': 'Take__styles__overlayItem'
};


// ================================
// the main component that students
// will use to take the quiz
// ================================

var Take = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(Take, _Component);

  function Take() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = Take.__proto__ || Object.getPrototypeOf(Take)).call.apply(_ref, [this].concat(args))), _this), _this.timerService = null, _this.fetchQuizSessionTimeout = null, _this.fetchQuizSession = function () {
      var _this$props = _this.props,
          fetchQuizSession = _this$props.fetchQuizSession,
          onTakeUnauthorized = _this$props.onTakeUnauthorized,
          quizSessionId = _this$props.quizSessionId;

      return fetchQuizSession(quizSessionId, _this.waitForQuizSessionToBeReady, onTakeUnauthorized);
    }, _this.waitForQuizSessionToBeReady = function () {
      var quizSession = _this.props.quizSession;

      if (quizSession.failedToStart()) {
        _this.clearFetchQuizSessionTimeout();
        return _this.props.onTakeFailed();
      }
      if (quizSession.inProgress() || quizSession.submitted()) {
        _this.clearFetchQuizSessionTimeout();
        return _this.onQuizSessionReady();
      }
      _this.fetchQuizSessionTimeout = setTimeout(function () {
        _this.fetchQuizSession();
      }, 1000);
    }, _this.autoSubmitQuiz = function () {
      var msg = 'Die Zeit ist abgelaufen. Ihr Leistungstest wurde abgegeben.';
      var noop = function noop() {};
      _this.props.closeSubmitConfirmationModal(_this.props.quizSessionId);
      _this.props.screenreaderNotification(msg);
      _this.props.submitQuiz(_this.props.quizSessionId, noop, true);
    }, _this.focusOnButton = function () {
      _this.overlayBtn.focus();
    }, _this.overlayBtnRef = function (node) {
      _this.overlayBtn = node;
    }, _this.applicationElement = function () {
      return (0, _ElementsForSelectors2.default)(_this.props.appContainer);
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(Take, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      this.takeQuiz();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      // Stop spamming time endpoint if the timer isn't running after
      // initial check
      if (this.timerService && !this.props.useTimer && prevProps.useTimer) {
        this.timerService.stop();
      }
      if (this.props.quizSessionId !== prevProps.quizSessionId) {
        this.takeQuiz();
      }
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      if (this.timerService) {
        this.timerService.stop();
      }
      this.props.takingActions.updateIsTaking(false);
      this.clearFetchQuizSessionTimeout();
    }
  }, {
    key: 'takeQuiz',
    value: function takeQuiz() {
      var _props = this.props,
          onTakeUnauthorized = _props.onTakeUnauthorized,
          quizSessionId = _props.quizSessionId,
          newQuizTakingSession = _props.newQuizTakingSession;

      newQuizTakingSession(quizSessionId, this.waitForQuizSessionToBeReady, onTakeUnauthorized);
    }
  }, {
    key: 'clearFetchQuizSessionTimeout',
    value: function clearFetchQuizSessionTimeout() {
      if (!this.fetchQuizSessionTimeout) return;
      clearTimeout(this.fetchQuizSessionTimeout);
      this.fetchQuizSessionTimeout = null;
    }
  }, {
    key: 'onQuizSessionReady',
    value: function onQuizSessionReady() {
      this.props.takingActions.updateIsTaking(true);
      var quizIsTimed = !!this.props.quizSession.endAt;

      if (this.props.useTimer && !this.quizIsFinished()) {
        this.timerService = quizIsTimed ? new _TimerService2.default((0, _partial2.default)(this.props.getTimeRemaining, this.props.quizSessionId), this.props.takingActions.updateTimerInfo, this.props.getTimerData, this.autoSubmitQuiz, this.props.addInfo) : new _TimeRecordingService2.default((0, _partial2.default)(this.props.recordQuizTime, this.props.quizSessionId), this.props.takingActions.updateTimerInfo);
        this.timerService.start();
      }

      this.props.onQuizSessionReadyForTaking(this.props.quizSession);
    }
  }, {
    key: 'quizIsFinished',
    value: function quizIsFinished() {
      var quizSession = this.props.quizSession;


      if (!quizSession.isLoaded()) {
        return false;
      }

      // in_progress is set async, so we'll also let pending determine the status here
      return !(quizSession.inProgress() || quizSession.pending()) || this.props.timeIsUp;
    }
  }, {
    key: 'liveRegion',
    value: function liveRegion() {
      return document.querySelector('[role="alert"][aria-live="assertive"]');
    }

    // =============
    //   RENDERING
    // =============

  }, {
    key: 'renderHeader',
    value: function renderHeader() {
      var currentSessionItemPosition = this.props.currentSessionItemPosition;

      if (!this.props.isOneQuestionAtATime || currentSessionItemPosition === 1) {
        return _react2.default.createElement(_TakeHeader2.default, {
          currentSessionItemPosition: currentSessionItemPosition,
          quizSessionId: this.props.quizSessionId
        });
      }
    }
  }, {
    key: 'renderOverlay',
    value: function renderOverlay() {
      var isOpen = this.quizIsFinished();
      var startedInProgress = this.props.quizSessionStatusOnPageLoad === _constants.IN_PROGRESS;
      var quizIsTimed = this.props.quizSession.get('endAt');

      var text = void 0;
      if (!isOpen) {
        text = '';
      } else if (!quizIsTimed) {
        text = 'Dieses Quiz wurde eingereicht.';
      } else if (startedInProgress) {
        text = 'Die Zeit ist um.';
      } else {
        text = 'Ihre Zeit f\xFCr dieses Quiz ist abgelaufen.';
      }

      return _react2.default.createElement(
        _Overlay2.default,
        {
          applicationElement: this.applicationElement,
          onEntered: this.focusOnButton,
          open: isOpen,
          shouldContainFocus: true,
          transition: 'fade'
        },
        _react2.default.createElement(
          _Mask2.default,
          null,
          _react2.default.createElement(
            'div',
            { className: styles.overlayBody },
            _react2.default.createElement(
              'div',
              { className: styles.overlayItem },
              _react2.default.createElement(
                'h2',
                null,
                text
              )
            ),
            _react2.default.createElement(
              'div',
              { className: styles.overlayItem },
              _react2.default.createElement(
                _Button2.default,
                {
                  ref: this.overlayBtnRef,
                  variant: 'primary',
                  onClick: this.props.onSubmitQuizSession,
                  'data-automation': 'sdk-go-to-results-button'
                },
                'Zu den Ergebnissen'
              )
            )
          )
        )
      );
    }
  }, {
    key: 'renderFailedToStart',
    value: function renderFailedToStart() {
      return _react2.default.createElement(
        _Alert2.default,
        { liveRegion: this.liveRegion, margin: 'large', variant: 'error' },
        'Etwas ging schief. Bitte versuchen Sie es noch einmal.'
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          currentSessionItemPosition = _props2.currentSessionItemPosition,
          isOneQuestionAtATime = _props2.isOneQuestionAtATime,
          onSubmitQuizSession = _props2.onSubmitQuizSession,
          quizSession = _props2.quizSession,
          quizSessionId = _props2.quizSessionId,
          resumeDataLoaded = _props2.resumeDataLoaded;


      if (quizSession.failedToStart()) {
        return this.renderFailedToStart();
      }
      var sessionItemsLoaded = quizSession.sessionItems && quizSession.sessionItems.first();
      var readyToTake = quizSession.sessionItemsCount === 0 || resumeDataLoaded && sessionItemsLoaded;

      if (!readyToTake) {
        return _react2.default.createElement(_Spinner2.default, null);
      }

      return _react2.default.createElement(
        _Page2.default,
        {
          contentRole: this.props.contentRole,
          sidebarComponent: _Sidebar2.default,
          sidebarOpen: this.props.sidebarOpen,
          sidebarRole: this.props.sidebarRole,
          toggleSidebar: this.props.toggleSidebar
        },
        _react2.default.createElement(
          _Card2.default,
          { wrapped: true, className: (0, _classnames2.default)((0, _defineProperty3.default)({}, styles.root, isOneQuestionAtATime)) },
          this.renderOverlay(),
          this.renderHeader(),
          _react2.default.createElement(
            'div',
            { 'data-automation': 'sdk-take-component' },
            _react2.default.createElement(_TakeBody2.default, {
              currentSessionItemPosition: currentSessionItemPosition,
              quizSessionId: quizSessionId
            })
          ),
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(_TakeFooter2.default, {
              currentSessionItemPosition: currentSessionItemPosition,
              onSubmitQuizSession: onSubmitQuizSession,
              quizSessionId: quizSessionId
            })
          )
        )
      );
    }
  }]);
  Take.displayName = 'Take'
  ;
  return Take;
}(_react.Component), _class2.propTypes = {
  addInfo: _propTypes2.default.func.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  closeSubmitConfirmationModal: _propTypes2.default.func.isRequired,
  currentSessionItemPosition: _propTypes2.default.number,
  fetchQuizSession: _propTypes2.default.func.isRequired,
  getTimeRemaining: _propTypes2.default.func.isRequired,
  getTimerData: _propTypes2.default.func.isRequired,
  isOneQuestionAtATime: _propTypes2.default.bool.isRequired,
  newQuizTakingSession: _propTypes2.default.func.isRequired,
  onQuizSessionReadyForTaking: _propTypes2.default.func.isRequired,
  onSubmitQuizSession: _propTypes2.default.func.isRequired, // consumer provided
  onTakeFailed: _propTypes2.default.func, // consumer provided
  onTakeUnauthorized: _propTypes2.default.func, // consumer provided
  quizSession: _reactImmutableProptypes2.default.record.isRequired,
  quizSessionId: _propTypes2.default.string.isRequired,
  quizSessionStatusOnPageLoad: _propTypes2.default.string.isRequired,
  recordQuizTime: _propTypes2.default.func.isRequired,
  resumeDataLoaded: _propTypes2.default.bool.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  submitQuiz: _propTypes2.default.func.isRequired,
  contentRole: _propTypes2.default.string,
  sidebarRole: _propTypes2.default.string,
  toggleSidebar: _propTypes2.default.func,
  sidebarOpen: _propTypes2.default.bool,
  takingActions: _propTypes2.default.shape({
    updateIsTaking: _propTypes2.default.func,
    updateTimerInfo: _propTypes2.default.func
  }).isRequired,
  timeIsUp: _propTypes2.default.bool,
  useTimer: _propTypes2.default.bool
}, _class2.defaultProps = {
  contentRole: void 0,
  sidebarRole: void 0,
  toggleSidebar: void 0,
  sidebarOpen: void 0,
  currentSessionItemPosition: 1,
  onSubmitQuizSession: function onSubmitQuizSession() {},
  onTakeFailed: function onTakeFailed() {},
  onTakeUnauthorized: function onTakeUnauthorized() {},

  timeIsUp: false,
  useTimer: true
}, _temp2)) || _class);
exports.default = Take;