'use strict';

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 = undefined;

var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');

var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);

var _Fetcher = require('../util/Fetcher');

var _Fetcher2 = _interopRequireDefault(_Fetcher);

var _withDynamoPagination = require('../util/withDynamoPagination');

var _withDynamoPagination2 = _interopRequireDefault(_withDynamoPagination);

var _noop = require('../util/noop');

var _noop2 = _interopRequireDefault(_noop);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

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

var _QuizSessionResult = require('../records/QuizSessionResult');

var _QuizSessionResult2 = _interopRequireDefault(_QuizSessionResult);

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

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

var generateUrl = function generateUrl(pathParts) {
  return ['', 'api', 'quiz_sessions'].concat((0, _toConsumableArray3.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 _Fetcher2.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, _withDynamoPagination2.default)(_Fetcher2.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 _Fetcher2.default(fetcherParams);
  return fetcher.post(url, params).then(responseCb);
};

// /////////////////////
//  GENERAL
// /////////////////////

var fetchQuizSession = exports.fetchQuizSession = function fetchQuizSession(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  return get(generateUrl([quizSessionId]), responseCb);
};

var fetchSessionItems = exports.fetchSessionItems = function fetchSessionItems(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  return dynamoGet(generateUrl([quizSessionId, 'session_items']), responseCb, { callType: _constants.SESSION_ITEMS_FETCH_CALL });
};

// //////////////////////
// BEFORE TAKING
// //////////////////////
var submitStudentAccessCode = exports.submitStudentAccessCode = function submitStudentAccessCode(quizSessionId, accessCode) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop2.default;

  return post(generateUrl([quizSessionId, 'submit_student_access_code']), { body: JSON.stringify({ accessCode: accessCode }) }, responseCb, {});
};

// //////////////////////
// TAKING
// //////////////////////

var takeQuizSession = exports.takeQuizSession = function takeQuizSession(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  // Avoid generating the error header; errors handled via catch
  return post(generateUrl([quizSessionId, 'take']), {}, responseCb, { onError: function onError() {
      return { type: _constants.DO_NOTHING };
    } });
};

var fetchResumeData = exports.fetchResumeData = function fetchResumeData(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.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
var pinSessionItem = exports.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);
  };
};

var fetchTime = exports.fetchTime = function fetchTime(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  return get(generateUrl([quizSessionId, 'time']), responseCb);
};

var recordTime = exports.recordTime = function recordTime(quizSessionId) {
  var responseCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _noop2.default;

  return get(generateUrl([quizSessionId, 'record']), responseCb);
};

// /////////////////////
//  TAKING SUBMIT
// /////////////////////

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)('Dette fors\xF8g blev allerede afleveret. Viser resultater fra forudg\xE5ende aflevering.');
    }
    return (0, _alerts.addError)('Afleveringsfejl. Vent venligst 10 sekunder, og pr\xF8v igen.');
  };
};

var singleResponseSubmit = exports.singleResponseSubmit = function singleResponseSubmit(quizSessionId, userResponse) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop2.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)
  });
};

var submitQuizSession = exports.submitQuizSession = function submitQuizSession(quizSessionId, userResponses) {
  var responseCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _noop2.default;

  return post(generateUrl([quizSessionId, 'submit']), userResponses, responseCb, { onError: onSubmitError(responseCb) });
};

// ///////////////////////////////
//  POST TAKING (RESULTS/GRADING)
// ///////////////////////////////

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

  return dynamoGet(generateUrl([quizSessionId, 'results', quizSessionResultId, 'session_item_results']), responseCb);
};

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

  var fetcherKey = _QuizSessionResult2.default.fetcherTag(quizSessionResultId);
  return get(generateUrl([quizSessionId, 'results', quizSessionResultId]), responseCb, { callType: fetcherKey }, true);
};