"use strict";

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

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.confirmSessionStartPage = confirmSessionStartPage;
exports.newQuizTakingSession = newQuizTakingSession;
exports.onQuizSessionReadyForTaking = onQuizSessionReadyForTaking;
exports.showSubmitConfirmModal = showSubmitConfirmModal;
exports.closeSubmitConfirmModal = closeSubmitConfirmModal;
exports.submitQuiz = submitQuiz;
exports.postQuizSession = postQuizSession;
exports.getTimeRemaining = getTimeRemaining;
exports.recordQuizTime = recordQuizTime;
exports.messageForSubmitModal = exports.nextQuestion = exports.submitStudentAccessCode = exports.makeSessionItemCall = exports.getResumeData = void 0;

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

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

var _immutable = require("immutable");

var _humps = require("humps");

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

var _noop = _interopRequireDefault(require("../../common/util/noop"));

var _alerts = require("../../common/actions/alerts");

var _Item = _interopRequireDefault(require("../../common/records/Item"));

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

var uiActions = _interopRequireWildcard(require("../../common/actions/ui"));

var _quizSessions = require("../../common/api/quizSessions");

var _quizSessions2 = require("../../common/actions/quizSessions");

var _callHandlers = require("../../common/api/callHandlers");

var modalActions = _interopRequireWildcard(require("../../common/actions/modal"));

var _taking = require("../../common/actions/taking");

var _default_nl_number = Intl.NumberFormat("nl", { style: "decimal" }).format;

var getQuizSessionConfig = function getQuizSessionConfig(quizSession) {
  // these should be handled by existing functions
  var oneQuestionAtATime = quizSession.isOneQuestionAtATime();
  var allowBacktracking = quizSession.allowBacktracking;
  var useSessionItemIndex = !oneQuestionAtATime || allowBacktracking;
  return {
    oneQuestionAtATime: oneQuestionAtATime,
    allowBacktracking: allowBacktracking,
    useSessionItemIndex: useSessionItemIndex
  };
};

var getResumeData = function getResumeData(quizSessionId) {
  return function (dispatch) {
    var responseCb = function responseCb(resumeData) {
      return dispatch((0, _callHandlers.handleResumeDataResponse)(resumeData, quizSessionId));
    };

    return (0, _quizSessions.fetchResumeData)(quizSessionId, responseCb);
  };
};

exports.getResumeData = getResumeData;

var makeSessionItemCall = function makeSessionItemCall(quizSession) {
  var index = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _quizSessions2.getSessionItems;
  var next = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : nextQuestion;
  return function (dispatch) {
    var action = getQuizSessionConfig(quizSession).useSessionItemIndex ? index(quizSession.id) : next(quizSession.id, false, false, null, null, null);
    return dispatch(action);
  };
};

exports.makeSessionItemCall = makeSessionItemCall;

var submitStudentAccessCode = function submitStudentAccessCode(quizSessionId, accessCode) {
  return function (dispatch) {
    var responseCb = function responseCb(sessionData) {
      dispatch(uiActions.set(_constants.STUDENT_ACCESS_CODE_STATUS, sessionData.accepted_student_access_code));

      if (sessionData.accepted_student_access_code) {
        dispatch((0, _alerts.screenreaderNotification)("Toegangscode gelukt. Je kunt nu aan deze opdracht beginnen"));
      } else {
        dispatch((0, _alerts.screenreaderNotification)("Ongeldige toegangscode"));
      }

      return dispatch((0, _callHandlers.handleQuizSessionResponse)(sessionData, quizSessionId));
    };

    return (0, _quizSessions.submitStudentAccessCode)(quizSessionId, accessCode, responseCb);
  };
}; // ====================================
// OQAAT no backtracking call
// ====================================


exports.submitStudentAccessCode = submitStudentAccessCode;

var noBacktrackingNextQuestion = function noBacktrackingNextQuestion(quizSessionId, itemId, userResponse, largeFormatResponse, submit) {
  return function (dispatch) {
    var params = {};

    if (itemId) {
      params.body = JSON.stringify({
        sessionItemResponse: {
          itemId: itemId,
          userResponse: userResponse,
          largeFormatResponse: largeFormatResponse
        }
      });
    }

    var responseCb = function responseCb(nextItem) {
      if (nextItem) {
        dispatch([(0, _callHandlers.handleSessionItemsResponse)([nextItem], quizSessionId), (0, _taking.setCurrentSessionItemPosition)(nextItem.position)]);
      } else {
        submit();
      }
    };

    return (0, _quizSessions.singleResponseSubmit)(quizSessionId, params, responseCb);
  };
}; // ====================================
// OQAAT no backtracking call
// ====================================


var nextQuestion = function nextQuestion(quizSessionId, allowBacktracking, currentQuestionIsLast, itemId, userResponse, largeFormatResponse) {
  var submit = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : submitQuiz;

  if (allowBacktracking) {
    return function (dispatch) {
      var action = currentQuestionIsLast ? submit(quizSessionId) : (0, _taking.backtrackingNextQuestion)();
      if (action) dispatch(action);
    };
  } else {
    return noBacktrackingNextQuestion(quizSessionId, itemId, userResponse, largeFormatResponse, submit);
  }
}; // ====================================
// load up the quiz session for the taking page
// ====================================


exports.nextQuestion = nextQuestion;

function confirmSessionStartPage(quizSessionId) {
  var cb = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _noop.default;
  var authRedirectCb = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : _noop.default;
  return function (dispatch) {
    return (0, _quizSessions.fetchQuizSession)(quizSessionId, (0, _partial.default)(_quizSessions2.handleQuizSessionFetch, dispatch)).then(cb).catch(function (e) {
      if (e.response && e.response.status === 403) {
        authRedirectCb();
      }
    });
  };
} // ====================================
// fetch the data for a new quiz_session
// ====================================


function newQuizTakingSession(quizSessionId) {
  var cb = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _noop.default;
  var authRedirectCb = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : _noop.default;
  return function (dispatch) {
    return (0, _quizSessions.takeQuizSession)(quizSessionId, (0, _partial.default)(_quizSessions2.handleQuizSessionFetch, dispatch)).then(cb).catch(function (e) {
      if (e.response.status === 403) {
        authRedirectCb();
      }
    });
  };
}

function onQuizSessionReadyForTaking(quizSession) {
  return function (dispatch) {
    dispatch([makeSessionItemCall(quizSession), getResumeData(quizSession.id), (0, _taking.sessionStartOrResumeEvent)(navigator.userAgent), (0, _taking.updateQuizSessionStatusOnPageLoad)(quizSession.status)]);
  };
} // ====================================
// show submit confirmation modal
// ====================================


var messageForSubmitModal = function messageForSubmitModal(positions) {
  if (!positions || positions.length === 0) {
    return "Na inlevering kun je je antwoorden niet meer wijzigen. Klaar om in te leveren?";
  }

  if (positions.length >= 10) {
    return "Er zijn meerdere vragen niet beantwoord. Na inlevering kun je je antwoorden niet meer wijzigen. Klaar om in te leveren?";
  }

  return _react.default.createElement("div", null, _react.default.createElement("p", null, "De volgende vragen zijn niet beantwoord:"), _react.default.createElement("ul", null, positions.map(function (position) {
    return _react.default.createElement("li", {
      key: position
    }, "Vraag " + _default_nl_number(position));
  })), _react.default.createElement("p", null, "Na inlevering kun je je antwoorden niet meer wijzigen. Klaar om in te leveren?"));
};

exports.messageForSubmitModal = messageForSubmitModal;

var __getResponseForSessionItem = function __getResponseForSessionItem(sessionItem, responses) {
  var resp = responses.find(function (r) {
    return r.get('position') === sessionItem.get('position');
  });
  return resp && resp.get('userResponse').toJS();
};

var __remainingQuestionPositions = function __remainingQuestionPositions(sessionItems, responses) {
  return sessionItems.toList().sortBy(function (si) {
    return si.get('position');
  }).filterNot(function (si) {
    var item = new _Item.default(si.get('item'));

    var itemUserResponse = __getResponseForSessionItem(si, responses);

    return item.hasResponse(itemUserResponse);
  }).map(function (si) {
    return si.get('position');
  }).toSet().toJS();
};

function showSubmitConfirmModal(quizSessionId) {
  var onSubmitQuizSession = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _noop.default;
  return function (dispatch, getState) {
    var needResponse = getQuestionsNeedingAResponse(getState(), quizSessionId);
    var title = titleForSubmitModal(needResponse);
    var message = messageForSubmitModal(needResponse);
    var modalAction = modalActions.withConfirm(function () {
      return dispatch(postQuizSession(quizSessionId, onSubmitQuizSession));
    }, {
      title: title,
      text: message,
      continueText: "Inleveren",
      cancelText: "Annuleren"
    });
    return dispatch(modalAction);
  };
}

function closeSubmitConfirmModal(quizSessionId) {
  return function (dispatch, getState) {
    var needResponse = getQuestionsNeedingAResponse(getState(), quizSessionId);
    var title = titleForSubmitModal(needResponse);
    return dispatch(modalActions.closeModal(title));
  };
}

function titleForSubmitModal(needResponse) {
  return needResponse.length > 0 ? "Onbeantwoorde vragen!" : "Inlevering bevestigen";
} // ==============================================
// check for unanswered questions or override
// ==============================================


function submitQuiz(quizSessionId) {
  var onSubmitQuizSession = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _noop.default;
  var overrideConfirmation = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
  return function (dispatch) {
    if (overrideConfirmation) {
      return dispatch(postQuizSession(quizSessionId, onSubmitQuizSession));
    } else {
      return dispatch(showSubmitConfirmModal(quizSessionId, onSubmitQuizSession));
    }
  };
}

function getQuestionsNeedingAResponse(state, quizSessionId) {
  var responses = state.getIn(['taking', 'responses'], (0, _immutable.Map)());
  var sessionItems = state.get('sessionItems', (0, _immutable.Map)()).filter(function (record) {
    return record.get('quizSessionId') === quizSessionId;
  });
  return __remainingQuestionPositions(sessionItems, responses);
} // ====================================
// submit the data for the quiz
// ====================================


function postQuizSession(quizSessionId) {
  var onSubmitQuizSession = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : _noop.default;
  return function (dispatch, getState) {
    var submitFlag = getState().getIn(['taking', 'submitFlag']);

    if (!submitFlag) {
      dispatch((0, _taking.updateQuizSubmitFlag)(true));
      var takingResponses = getState().getIn(['taking', 'responses'], (0, _immutable.Map)()).valueSeq().toJS();
      var params = {
        body: JSON.stringify({
          session_item_responses: takingResponses
        })
      };
      var submitQuizSessionEventAction = (0, _taking.submitQuizSessionEvent)();

      var responseCb = function responseCb() {
        dispatch((0, _alerts.screenreaderNotification)("Toets ingeleverd"));
        onSubmitQuizSession();
        dispatch(submitQuizSessionEventAction);
      };

      return (0, _quizSessions.submitQuizSession)(quizSessionId, params, responseCb);
    }
  };
} // ====================================
//  getting the remaining time
// ====================================


function getTimeRemaining(quizSessionId, cb) {
  return function (dispatch) {
    return (0, _quizSessions.fetchTime)(quizSessionId, function (result) {
      return cb((0, _humps.camelizeKeys)(result));
    });
  };
} // ====================================
//  tracking time taken
// ====================================


function recordQuizTime(quizSessionId, cb) {
  return function (dispatch) {
    return (0, _quizSessions.recordTime)(quizSessionId, function (result) {
      return cb((0, _humps.camelizeKeys)(result));
    });
  };
}