"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.quizBuildingSession = quizBuildingSession;
exports.saveQuizChange = saveQuizChange;
exports.startNewQuiz = startNewQuiz;
exports.getExistingQuizAndItemsForBuilding = getExistingQuizAndItemsForBuilding;
exports.interactionFileUpload = interactionFileUpload;
exports.setQuizShuffleQuestions = setQuizShuffleQuestions;
exports.setRequireStudentAccessCode = setRequireStudentAccessCode;
exports.setStudentAccessCodeUi = setStudentAccessCodeUi;
exports.setStudentAccessCodeApi = setStudentAccessCodeApi;
exports.setOneAtATimeType = setOneAtATimeType;
exports.setBacktracking = setBacktracking;
exports.setQuizHasTimeLimit = setQuizHasTimeLimit;
exports.setSessionTimeLimitInSecondsUi = setSessionTimeLimitInSecondsUi;
exports.setSessionTimeLimitInSecondsApi = setSessionTimeLimitInSecondsApi;
exports.setFilterIpAddress = setFilterIpAddress;
exports.setIpFiltersUi = setIpFiltersUi;
exports.setIpFiltersApi = setIpFiltersApi;
exports.setCalculatorType = setCalculatorType;

var _immutable = require("immutable");

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

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

var _qtiImports = require("./qtiImports");

var _modifications = require("../../common/actions/modifications");

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

var _fileUpload = require("../../common/api/fileUpload");

var _interactionTypes = require("../../common/api/interactionTypes");

var _quizzes = require("../../common/api/quizzes");

var config = require('../../config');

var quizApiEndpoint = '/api/quizzes'; // ==== CALLBACKS ====

var handleQuizFetch = function handleQuizFetch(dispatch, quiz) {
  (0, _quizzes.quizFetchHandler)(dispatch, quiz); // if feature is on, fetch qti import data

  dispatch((0, _qtiImports.getQTIInfo)(quiz.id));
}; // ==================
// ==========================================
// called by the router when a quiz is needed
// knows how to create a new quiz, fetch
// an existing quiz, or set activeId depending
// on the current state & params
// ==========================================


function quizBuildingSession(routerParams) {
  return function (dispatch, getState) {
    var contextId = routerParams.contextId;
    var quizId = routerParams.activeQuizId;
    var createNew = routerParams.createNew;
    var needsQuiz = quizId === _constants.NEW_QUIZ_ID || !quizId; // create a new quiz if none exists

    if (createNew && needsQuiz) {
      return dispatch(startNewQuiz(contextId));
    } // do nothing if already on quiz and questions are loaded


    var currentQuizId = getState().getIn(['quizzes', 'activeQuizId']);
    var quizEntries = getState().get('quizEntries', (0, _immutable.Map)());

    if (currentQuizId === quizId && quizEntries.size > 0) {
      return {
        type: _constants.DO_NOTHING
      };
    }

    dispatch(getExistingQuizAndItemsForBuilding(quizId));
  };
} // ====================================
// save quiz changed, and on success
// add these changes to the quiz store
// ====================================


function saveQuizChange(workingQuiz, quiz) {
  if (workingQuiz.equals(quiz)) {
    // cannot just return null since
    // dispatch expects an action
    return {
      type: _constants.DO_NOTHING
    };
  }

  var url = "".concat(quizApiEndpoint, "/").concat(workingQuiz.get('id'));
  var quizData = JSON.stringify(workingQuiz.validData().toJS());
  return function (dispatch, getState) {
    var params = {
      body: quizData
    };
    var fetcher = new _Fetcher.default({
      callType: _constants.QUIZ_SAVE_CALL
    });
    return fetcher.patch(url, params).then(function (quizData) {
      dispatch((0, _callHandlers.handleQuizResponse)(quizData));
    });
  };
} // =================================
// create a new quiz, add its data,
// and add it as the active quiz
// =================================


function startNewQuiz(contextId) {
  return function (dispatch, getState) {
    var newQuizData = JSON.stringify({
      title: 'Add Title...',
      context_id: contextId || config.defaultContextId
    });
    var params = {
      body: newQuizData
    };
    var fetcher = new _Fetcher.default();
    return fetcher.post(quizApiEndpoint, params).then(function (quizData) {
      handleQuizFetch(dispatch, quizData);
    }).then(function () {
      dispatch((0, _interactionTypes.interactionTypeFetch)());
    });
  };
} // ====================================
// fetch the data for an existing quiz
// and add it as the active quiz
// ====================================


function getExistingQuizAndItemsForBuilding(quizId) {
  var fetchTags = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  // TODO: handleQuizFetch is not handled in getExistingQuizAndItems,
  //       so determine impact of getQTIInfo not being dispatched
  return (0, _quizzes.getExistingQuizAndItems)(quizId, fetchTags, handleQuizFetch);
} // =========================================
//  media upload endpoint funcs
// =========================================


function getPathToGetUrl(parentType, parentId) {
  switch (parentType) {
    case _constants.PARENT_TYPE_BANK:
      return "/api/banks/".concat(parentId, "/items/media_upload_url");

    case _constants.PARENT_TYPE_QUIZ:
      return "/api/quizzes/".concat(parentId, "/items/media_upload_url");

    case _constants.PARENT_TYPE_QUIZ_SESSION:
      return "/api/quiz_sessions/".concat(parentId, "/media_upload_url");
  }
}

function interactionFileUpload(parentType, parentId, file, onSuccess, onError, uploadPath) {
  var withUrlCallback = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : _fileUpload.sendFileToS3;
  return function (dispatch, getState) {
    var pathToGetUrl = uploadPath || getPathToGetUrl(parentType, parentId);
    return (0, _fileUpload.getUploadUrl)(pathToGetUrl).then(withUrlCallback(file, onSuccess, onError));
  };
} // ====================================
// update the data for an existing quiz
// ====================================


function setQuizProperty(quizId, properties, action) {
  var url = "/api/quizzes/".concat(quizId);
  var body = JSON.stringify({
    id: quizId,
    quiz: properties
  });
  return function (dispatch, getState) {
    var params = {
      body: body
    };
    var fetcher = new _Fetcher.default({
      callType: _constants.QUIZ_SAVE_CALL
    });

    if (action !== null) {
      dispatch(action);
    }

    return fetcher.patch(url, params).then(function (response) {
      dispatch((0, _callHandlers.handleQuizResponse)(response));
    });
  };
}

function setQuizShuffleQuestions(quizId, value) {
  return setQuizProperty(quizId, {
    shuffle_questions: Boolean(value)
  }, (0, _modifications.changeQuizShuffleQuestions)(quizId, value));
}

function setRequireStudentAccessCode(quizId, value) {
  return setQuizProperty(quizId, {
    require_student_access_code: Boolean(value)
  }, (0, _modifications.changeQuizRequireStudentAccessCode)(quizId, value));
}

function setStudentAccessCodeUi(quizId, value) {
  return function (dispatch, getState) {
    dispatch((0, _modifications.changeQuizStudentAccessCode)(quizId, value));
  };
}

function setStudentAccessCodeApi(quizId, value) {
  return setQuizProperty(quizId, {
    student_access_code: value
  }, null);
}

function setOneAtATimeType(quizId, checked) {
  var oneAtATimeType = checked ? 'question' : null;
  return setQuizProperty(quizId, {
    one_at_a_time_type: oneAtATimeType
  }, (0, _modifications.changeQuizOneAtATimeType)(quizId, oneAtATimeType));
}

function setBacktracking(quizId, value) {
  return setQuizProperty(quizId, {
    allow_backtracking: Boolean(value)
  }, (0, _modifications.changeQuizAllowBacktracking)(quizId, value));
}

function setQuizHasTimeLimit(quizId, value) {
  return setQuizProperty(quizId, {
    has_time_limit: Boolean(value)
  }, (0, _modifications.changeQuizHasTimeLimit)(quizId, value));
}

function setSessionTimeLimitInSecondsUi(quizId, value) {
  return function (dispatch, getState) {
    dispatch((0, _modifications.changeSessionTimeLimitInSeconds)(quizId, value));
  };
}

function setSessionTimeLimitInSecondsApi(quizId, value) {
  return setQuizProperty(quizId, {
    session_time_limit_in_seconds: value
  }, null);
}

function setFilterIpAddress(quizId, value) {
  return setQuizProperty(quizId, {
    filter_ip_address: Boolean(value)
  }, (0, _modifications.changeQuizFilterIpAddress)(quizId, value));
}

function setIpFiltersUi(quizId, value) {
  return function (dispatch, getState) {
    dispatch((0, _modifications.changeQuizIpFilters)(quizId, value));
  };
}

function setIpFiltersApi(quizId, value) {
  return setQuizProperty(quizId, {
    filters: {
      ips: value
    }
  }, null);
}

function setCalculatorType(quizId, value) {
  return setQuizProperty(quizId, {
    calculator_type: value
  }, (0, _modifications.changeQuizCalculatorType)(quizId, value));
}