'use strict';

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

var _omit = require('lodash/omit');

var _omit2 = _interopRequireDefault(_omit);

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

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

var _Fetcher2 = _interopRequireDefault(_Fetcher);

var _postMessage = require('../../common/actions/postMessage');

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

var _quizSessions = require('../../common/actions/quizSessions');

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

var removeIdsFromModifications = function removeIdsFromModifications(modifiedResults) {
  return modifiedResults.map(function (result) {
    return (0, _omit2.default)(result, 'id');
  });
};

var postQuizSessionResults = exports.postQuizSessionResults = function postQuizSessionResults(sessionId, sessionItemResultsModifications, fudgePoints) {
  var fetchQuizSessionCb = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _quizSessions.getResultInfo;

  var quizSessionUrl = '/api/quiz_sessions/' + sessionId;
  var url = quizSessionUrl + '/results';

  return function (dispatch, getState) {
    var fetchLib = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : fetch;

    var modifiedResultsWithoutIds = removeIdsFromModifications(sessionItemResultsModifications);

    var params = {
      body: JSON.stringify({
        results: modifiedResultsWithoutIds,
        fudge_points: fudgePoints
      })
    };

    var fetcher = new _Fetcher2.default();
    return fetcher.post(url, params).then(function (quizSessionResult) {
      return dispatch([(0, _postMessage.postToParent)({ subject: _constants.SUBMISSION_UPDATE_SUBJECT }), (0, _callHandlers.handleQuizSessionResultsResponse)([quizSessionResult]), fetchQuizSessionCb(sessionId)]);
    });
  };
};