"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getItem = getItem;
exports.createItem = createItem;
exports.updateItem = updateItem;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

var _first = _interopRequireDefault(require("lodash/first"));

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

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

var _helpers = require("../../common/api/helpers");

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

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

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

// =========================================
// =========================================
//  this file is in charge of coordinating
//  the dispatching of actions necessary
//  to interact with items via the api
// =========================================
// =========================================
// =====================
// =====================
//       CREATE
// =====================
// =====================
function getItem(itemId) {
  var url = "/api/items/".concat(itemId);
  return function (dispatch, getState) {
    var fetcher = new _Fetcher.default();
    return fetcher.get(url).then(function (itemData) {
      dispatch((0, _callHandlers.handleItemsResponse)([itemData]));
      return itemData;
    });
  };
}

function createItem(item, parentId, parentType) {
  var parentItemId = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null;
  var resource = parentType === 'bank' ? 'banks' : 'quizzes';
  var url = "/api/".concat(resource, "/").concat(parentId, "/items");
  var itemParams = {
    feedback: item.feedback,
    interaction_data: item.interactionData,
    interaction_type_id: item.interactionType,
    item_body: item.itemBody,
    outcome_alignment_set_guid: item.outcomeAlignmentSetGuid,
    parent_item_id: parentItemId,
    properties: item.properties,
    scoring_algorithm: item.getScoringAlgorithm(),
    scoring_data: item.scoringData,
    title: item.title,
    user_response_type: (0, _first.default)(item.getInteractionType().userResponseTypeOptions),
    stimulus_id: item.stimulusId,
    calculator_type: item.calculatorType,
    answer_feedback: item.answerFeedback
  };
  var requestBody = JSON.stringify({
    item: itemParams
  });
  return function (dispatch, getState) {
    var errorMessage = "Failed to create item.";
    var fetcher = new _Fetcher.default({
      callType: _constants.CREATE_ITEM_CALL,
      onError: parentType === 'bank' ? (0, _helpers.handleError)(dispatch, errorMessage) : function () {
        return (0, _alerts.addError)(errorMessage);
      }
    });
    var createItemParams = {
      body: requestBody
    };
    return fetcher.post(url, createItemParams).then(function (itemData) {
      dispatch((0, _callHandlers.handleItemsResponse)([itemData]));
      return itemData;
    });
  };
} // =====================
// =====================
//       UPDATE
// =====================
// =====================


function updateItem(item, parentId, parentType) {
  var resource = parentType === 'bank' ? 'banks' : 'quizzes';
  var url = "/api/".concat(resource, "/").concat(parentId, "/items/").concat(item.id);
  var itemData = {
    item_body: item.itemBody,
    title: item.title,
    scoring_data: item.scoringData,
    scoring_algorithm: item.getScoringAlgorithm(),
    interaction_data: item.interactionData,
    properties: item.properties,
    outcome_alignment_set_guid: item.outcomeAlignmentSetGuid,
    feedback: item.feedback,
    calculator_type: item.calculatorType,
    answer_feedback: item.answerFeedback
  };
  var reqBody = JSON.stringify({
    item: itemData
  });
  return function (dispatch, getState) {
    var updateItemParams = {
      body: reqBody
    };
    var fetcher = new _Fetcher.default({
      callType: _constants.UPDATE_ITEM_CALL,
      onError: function onError(_ref) {
        var response = _ref.response;
        return (
          /*#__PURE__*/
          function () {
            var _ref2 = (0, _asyncToGenerator2.default)(
            /*#__PURE__*/
            _regenerator.default.mark(function _callee(dispatch) {
              var _ref3, errors;

              return _regenerator.default.wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      if (!(response && response.status === 422)) {
                        _context.next = 12;
                        break;
                      }

                      _context.prev = 1;
                      _context.next = 4;
                      return response.json();

                    case 4:
                      _ref3 = _context.sent;
                      errors = _ref3.errors;

                      if (!(errors.base && errors.base.some(function (message) {
                        return message.includes('cannot update an immutable item');
                      }))) {
                        _context.next = 8;
                        break;
                      }

                      return _context.abrupt("return", dispatch((0, _alerts.addError)("This item has now been viewed by a student, so your edits were not saved. Please refresh the page and try again.")));

                    case 8:
                      _context.next = 12;
                      break;

                    case 10:
                      _context.prev = 10;
                      _context.t0 = _context["catch"](1);

                    case 12:
                      return _context.abrupt("return", dispatch((0, _alerts.addError)("Failed to update item.")));

                    case 13:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee, null, [[1, 10]]);
            }));

            return function (_x) {
              return _ref2.apply(this, arguments);
            };
          }()
        );
      }
    });
    return fetcher.patch(url, updateItemParams).then(function (itemData) {
      dispatch((0, _callHandlers.handleItemsResponse)([itemData]));
      return itemData;
    });
  };
}