"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.fetchQuizSessionResult = exports.fetchSessionItemResults = exports.submitQuizSession = exports.singleResponseSubmit = exports.recordTime = exports.fetchTime = exports.pinSessionItem = exports.fetchResumeData = exports.takeQuizSession = exports.submitStudentAccessCode = exports.fetchSessionItems = exports.fetchQuizSession = void 0;

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

var _Fetcher = _interopRequireDefault(require("../util/Fetcher"));

var _withDynamoPagination = _interopRequireDefault(require("../util/withDynamoPagination"));

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

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

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

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

var _QuizSessionResult = _interopRequireDefault(require("../records/QuizSessionResult"));

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

var generateUrl = function generateUrl(pathParts) {
  return ['', 'api', 'quiz_sessions'].concat((0, _toConsumableArray2.default)(pathParts)).join('/');
};

var get = function get(url, responseCb) {
  var fetcherParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var markCallbacksComplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  var fetcher = new _Fetcher.default(fetcherParams);
  var getCall = fetcher.get(url).then(responseCb);

  if (markCallbacksComplete) {
    return getCall.then(function () {
      return fetcher.markCallbacksComplete();
    });
  }

  return getCall;
};

var dynamoGet = function dynamoGet(url, responseCb) {
  var fetcherParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var markCallbacksComplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  var DynamoFetcher = (0, _withDynamoPagination.default)(_Fetcher.default);
  var DynamoFetcherGet = new DynamoFetcher(fetcherParams);
  var getCall = DynamoFetcherGet.paginatedGet(url).then(responseCb);

  if (markCallbacksComplete) {
    return getCall.then(function () {
      return DynamoFetcherGet.markCallbacksComplete();
    });
  }

  return getCall;
};

var post = function post(url, params, responseCb) {
  var fetcherParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var fetcher = new _Fetcher.default(fetcherParams);
  return fetcher.post(url, params).then(responseCb);
}; // /////////////////////
//  GENERAL
// /////////////////////


var fetchQuizSession = function fetchQuizSession(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  return get(generateUrl([quizSessionId]), responseCb);
};

exports.fetchQuizSession = fetchQuizSession;

var fetchSessionItems = function fetchSessionItems(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  return dynamoGet(generateUrl([quizSessionId, 'session_items']), responseCb, {
    callType: _constants.SESSION_ITEMS_FETCH_CALL
  });
}; // //////////////////////
// BEFORE TAKING
// //////////////////////


exports.fetchSessionItems = fetchSessionItems;

var submitStudentAccessCode = function submitStudentAccessCode(quizSessionId, accessCode) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop.default;
  return post(generateUrl([quizSessionId, 'submit_student_access_code']), {
    body: JSON.stringify({
      accessCode: accessCode
    })
  }, responseCb, {});
}; // //////////////////////
// TAKING
// //////////////////////


exports.submitStudentAccessCode = submitStudentAccessCode;

var takeQuizSession = function takeQuizSession(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  // Avoid generating the error header; errors handled via catch
  return post(generateUrl([quizSessionId, 'take']), {}, responseCb, {
    onError: function onError() {
      return {
        type: _constants.DO_NOTHING
      };
    }
  });
};

exports.takeQuizSession = takeQuizSession;

var fetchResumeData = function fetchResumeData(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  return get(generateUrl([quizSessionId, 'session_item_responses', 'resume_data']), responseCb);
}; // This is too widely used to be updated to use the common pattern here, fine as is


exports.fetchResumeData = fetchResumeData;

var pinSessionItem = function pinSessionItem(quizSessionId, sessionItemPosition) {
  return function (dispatch, getState) {
    var responseCb = function responseCb(quizSessionData) {
      return dispatch((0, _callHandlers.handleQuizSessionResponse)(quizSessionData));
    };

    var params = {
      body: JSON.stringify({
        position: sessionItemPosition
      })
    };
    return post(generateUrl([quizSessionId, 'toggle_session_item_pin']), params, responseCb);
  };
};

exports.pinSessionItem = pinSessionItem;

var fetchTime = function fetchTime(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  return get(generateUrl([quizSessionId, 'time']), responseCb);
};

exports.fetchTime = fetchTime;

var recordTime = function recordTime(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop.default;
  return get(generateUrl([quizSessionId, 'record']), responseCb);
}; // /////////////////////
//  TAKING SUBMIT
// /////////////////////


exports.recordTime = recordTime;

var onSubmitError = function onSubmitError(responseCb) {
  return function (error) {
    if (error.response && error.response.status === 422) {
      responseCb(); // responseCb is the page navigation to Results (comes from quiz_lti)

      return (0, _alerts.addError)("Tantativ sa a soum\xE8t deja. Afichaj rezilta soumisyon anvan an.");
    }

    return (0, _alerts.addError)("Er\xE8 soumisyon. Tanpri tann 10 segonn epi eseye ank\xF2.");
  };
};

var singleResponseSubmit = function singleResponseSubmit(quizSessionId, userResponse) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop.default;

  // if the server returns a 204, don't try to JSON deserialize the
  // empty response (204 = No Content)
  var asyncResponseHandler = function asyncResponseHandler(resp) {
    return resp.status === 204 ? Promise.resolve(null) : resp.json();
  };

  return post(generateUrl([quizSessionId, 'session_item_responses', 'single_response_submit']), userResponse, responseCb, {
    asyncResponseHandler: asyncResponseHandler,
    callType: _constants.OQAAT_NO_BACKTRACKING_NEXT_ITEM_FETCH_CALL,
    onError: onSubmitError(responseCb)
  });
};

exports.singleResponseSubmit = singleResponseSubmit;

var submitQuizSession = function submitQuizSession(quizSessionId, userResponses) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop.default;
  return post(generateUrl([quizSessionId, 'submit']), userResponses, responseCb, {
    onError: onSubmitError(responseCb)
  });
}; // ///////////////////////////////
//  POST TAKING (RESULTS/GRADING)
// ///////////////////////////////


exports.submitQuizSession = submitQuizSession;

var fetchSessionItemResults = function fetchSessionItemResults(quizSessionId, quizSessionResultId) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop.default;
  return dynamoGet(generateUrl([quizSessionId, 'results', quizSessionResultId, 'session_item_results']), responseCb);
};

exports.fetchSessionItemResults = fetchSessionItemResults;

var fetchQuizSessionResult = function fetchQuizSessionResult(quizSessionId, quizSessionResultId) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop.default;

  var fetcherKey = _QuizSessionResult.default.fetcherTag(quizSessionResultId);

  return get(generateUrl([quizSessionId, 'results', quizSessionResultId]), responseCb, {
    callType: fetcherKey
  }, true);
};

exports.fetchQuizSessionResult = fetchQuizSessionResult;