"use strict";

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

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

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

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

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

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

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

// =====================
// =====================
//       CREATE
// =====================
// =====================
function createStimulus(stimulus, parentId, parentType) {
  var parentStimulusId = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  var resource = parentType === 'bank' ? 'banks' : 'quizzes';
  var url = "/api/".concat(resource, "/").concat(parentId, "/stimuli");
  var stimulusParams = {
    body: stimulus.body,
    instructions: stimulus.instructions,
    parent_stimulus_id: parentStimulusId,
    source_url: stimulus.sourceUrl,
    stimulus_type: stimulus.stimulusType,
    title: stimulus.title
  };
  var requestBody = JSON.stringify({
    stimulus: stimulusParams
  });
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default({
      callType: _constants.CREATE_STIMULUS_CALL,
      onError: function onError() {
        return (0, _alerts.addError)("Error al crear un est\xEDmulo.");
      }
    });
    var createStimulusParams = {
      body: requestBody
    };
    return fetcher.post(url, createStimulusParams).then(function (stimulusData) {
      dispatch((0, _callHandlers.handleStimuliResponse)([stimulusData]));
      return stimulusData;
    });
  };
} // =====================
// =====================
//       UPDATE
// =====================
// =====================


function updateStimulus(stimulus, parentId, parentType) {
  var resource = parentType === 'bank' ? 'banks' : 'quizzes';
  var url = "/api/".concat(resource, "/").concat(parentId, "/stimuli/").concat(stimulus.id);
  var stimulusData = {
    title: stimulus.title,
    instructions: stimulus.instructions,
    body: stimulus.body,
    source_url: stimulus.sourceUrl
  };
  var reqBody = JSON.stringify({
    stimulus: stimulusData
  });
  return function (dispatch, getState) {
    var updateStimulusParams = {
      body: reqBody
    };
    var fetcher = new _Fetcher.default({
      callType: _constants.UPDATE_STIMULUS_CALL,
      onError: function onError() {
        return (0, _alerts.addError)("Error al actualizar el est\xEDmulo.");
      }
    });
    return fetcher.patch(url, updateStimulusParams).then(function (stimulusData) {
      dispatch((0, _callHandlers.handleStimuliResponse)([stimulusData]));
      return stimulusData;
    });
  };
}