"use strict";

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

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

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

var _chai = require("chai");

var _InteractionType = _interopRequireDefault(require("quiz-interactions/lib/records/InteractionType"));

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

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

var _callHelpers = require("../../../common/util/callHelpers");

var _items = require("../items");

var _items2 = require("../../../common/actions/items");

var _Item = _interopRequireDefault(require("../../../common/records/Item"));

var _fakeFetch = _interopRequireDefault(require("../../../../tests/util/fakeFetch"));

var _jsonify = require("../../../common/util/jsonify");

describe('items api actions creators', function () {
  var dispatchStub = sinon.stub();
  var getStateStub = sinon.stub();
  var fetchStub = sinon.stub();
  useFakeFetching({
    dispatchStub: dispatchStub,
    getStateStub: getStateStub,
    fetchStub: fetchStub
  });
  var quizId = '22';
  var position = 3;
  var item = new _Item.default({
    id: '22',
    itemBody: 'itemBody',
    title: 'the title',
    position: position,
    properties: {},
    scoringData: 'answer',
    interactionType: 3,
    outcomeAlignmentSetGuid: 'ce39d262-b8f6-4650-91c1-5a76b2c18f70',
    interactionData: 'foo',
    stimulusId: '4',
    calculatorType: 'basic'
  });
  describe('getItem', function () {
    var itemId = '1';

    var stubbedGetItemCall = function stubbedGetItemCall() {
      var getItemThunk = (0, _items.getItem)(itemId);
      getItemThunk(dispatchStub, getStateStub);
    };

    it('should hit the right endpoint', function () {
      stubbedGetItemCall();
      (0, _chai.expect)(fetchStub.calledWith("/api/items/".concat(itemId))).to.be.true();
    });
  });
  describe('createItem', function () {
    afterEach(function () {
      item.getInteractionType.restore && item.getInteractionType.restore();
    });
    var quizEntry = {
      position: 8,
      pointsPossible: 18
    };

    var stubbedCreateItemCall = function stubbedCreateItemCall() {
      var qiData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : quizEntry;
      var interactionType = new _InteractionType.default({
        scoringAlgorithmOptions: ['string'],
        userResponseTypeOptions: ['string'],
        scoringAlgorithmDefault: 'string'
      });
      sinon.stub(item, 'getInteractionType').returns(interactionType);
      _Fetcher.default.fakeFetch = fetchStub;
      var createItemThunk = (0, _items.createItem)(item, '3', 'quiz', 1);
      createItemThunk(dispatchStub, getStateStub);
    };

    it('should mark the create item call as started', function () {
      var createCallAction = (0, _callHelpers.startCallFor)(_constants.CREATE_ITEM_CALL);
      stubbedCreateItemCall();
      checkActionDispatched(dispatchStub, createCallAction);
    });
    it('should hit the right endpoint', function () {
      stubbedCreateItemCall();
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes/3/items')).to.be.true();
    });
    it('should serialize data properly', function () {
      stubbedCreateItemCall();
      var expectedData = JSON.stringify({
        item: {
          feedback: {},
          interaction_data: 'foo',
          interaction_type_id: 3,
          item_body: 'itemBody',
          outcome_alignment_set_guid: 'ce39d262-b8f6-4650-91c1-5a76b2c18f70',
          parent_item_id: 1,
          properties: {},
          scoring_algorithm: 'string',
          scoring_data: 'answer',
          title: 'the title',
          user_response_type: 'string',
          stimulus_id: '4',
          calculator_type: 'basic'
        }
      });
      (0, _chai.expect)(fetchStub.getCall(0).args[1].body).to.be.eql(expectedData);
    });

    var fakeGetQuizEntryActionCreator = function fakeGetQuizEntryActionCreator() {
      return {
        type: 'FAKE_GET_QUIZ_ENTRY'
      };
    };

    var fakeCreateItem = function fakeCreateItem() {
      var response = (0, _jsonify.jsoniblePromise)(item.toJS());
      var fakeFetch = (0, _fakeFetch.default)(response);
      var interactionType = new _InteractionType.default({
        scoringAlgorithmOptions: ['string'],
        userResponseTypeOptions: ['string']
      });
      sinon.stub(item, 'getInteractionType').returns(interactionType);
      _Fetcher.default.fakeFetch = fakeFetch;
      var createItemThunk = (0, _items.createItem)(item, {
        position: 8
      }, {
        getQuizEntriesActionCreator: fakeGetQuizEntryActionCreator
      });
      return createItemThunk(dispatchStub, getStateStub);
    };

    it('should mark the create call as a success on return', function (done) {
      var successfulCreate = (0, _callHelpers.successCallFor)(_constants.CREATE_ITEM_CALL);
      var fetchPromise = fakeCreateItem();
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, successfulCreate);
        done();
      });
    });
    it('should try to add the item to the store', function (done) {
      var fetchPromise = fakeCreateItem();
      var handleItemsAction = (0, _items2.addItems)([item.toJS()]);
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, handleItemsAction);
        done();
      });
    });
  });
  describe('updateItem', function () {
    var itemData = {
      id: '2',
      itemBody: 'new body',
      title: 'a new title',
      scoringData: '22',
      scoringAlgorithm: 'UpdatedAlgo',
      interactionData: {},
      properties: {},
      outcomeAlignmentSetGuid: '0281acd1-431a-4c94-a9cd-ba3429b887e6',
      calculatorType: 'basic'
    };

    var stubbedUpdateItemCall = function stubbedUpdateItemCall() {
      _Fetcher.default.fakeFetch = fetchStub;
      var item = new _Item.default(itemData);
      var updateItemThunk = (0, _items.updateItem)(item, quizId);
      updateItemThunk(dispatchStub, getStateStub);
    };

    it('should hit the right endpoint', function () {
      stubbedUpdateItemCall();
      (0, _chai.expect)(fetchStub.calledWith("/api/quizzes/".concat(quizId, "/items/2"))).to.be.true();
    });
    it('should mark the update item call as started', function () {
      stubbedUpdateItemCall();
      var updateCallStartAction = (0, _callHelpers.startCallFor)(_constants.UPDATE_ITEM_CALL);
      checkActionDispatched(dispatchStub, updateCallStartAction);
    });
    it('should serialize data properly', function () {
      stubbedUpdateItemCall();
      var expectedData = JSON.stringify({
        item: {
          item_body: 'new body',
          title: 'a new title',
          scoring_data: '22',
          scoring_algorithm: 'UpdatedAlgo',
          interaction_data: {},
          properties: {},
          outcome_alignment_set_guid: '0281acd1-431a-4c94-a9cd-ba3429b887e6',
          feedback: {},
          calculator_type: 'basic'
        }
      });
      (0, _chai.expect)(fetchStub.getCall(0).args[1].body).to.be.eql(expectedData);
    });

    var fakeUpdateItem = function fakeUpdateItem() {
      var response = (0, _jsonify.jsoniblePromise)(itemData);
      var fakeFetch = (0, _fakeFetch.default)(response);
      _Fetcher.default.fakeFetch = fakeFetch;
      var item = new _Item.default(itemData);
      var updateItemThunk = (0, _items.updateItem)(item, quizId);
      return updateItemThunk(dispatchStub, getStateStub);
    };

    it('should mark the update call as a success on return', function (done) {
      var fetchPromise = fakeUpdateItem();
      var successfulUpdate = (0, _callHelpers.successCallFor)(_constants.UPDATE_ITEM_CALL);
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, successfulUpdate);
        done();
      });
    });
    it('should try to update the item in the store', function (done) {
      var fetchPromise = fakeUpdateItem();
      var handleItemAction = (0, _items2.addItems)([itemData]);
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, handleItemAction);
        done();
      });
    });
    context('when a student has already started answering the question', function () {
      beforeEach(function () {
        var body = {
          errors: {
            base: ['cannot update an immutable item']
          }
        };
        var blob = new Blob([JSON.stringify(body)], {
          type: 'application/json'
        });
        var response = new Response(blob, {
          status: '422',
          statusText: 'Unprocessable Entity'
        });
        fetchStub.resolves(response);
      });
      it('displays an alert',
      /*#__PURE__*/
      (0, _asyncToGenerator2.default)(
      /*#__PURE__*/
      _regenerator.default.mark(function _callee() {
        var thunks, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, thunk;

        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return stubbedUpdateItemCall();

              case 2:
                // TODO: use redux-mock-store everywhere so we don't have to do this dance
                thunks = dispatchStub.getCalls().map(function (call) {
                  return call.args[0];
                }).filter(function (arg) {
                  return typeof arg === 'function';
                });
                _iteratorNormalCompletion = true;
                _didIteratorError = false;
                _iteratorError = undefined;
                _context.prev = 6;
                _iterator = thunks[Symbol.iterator]();

              case 8:
                if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
                  _context.next = 15;
                  break;
                }

                thunk = _step.value;
                _context.next = 12;
                return thunk(dispatchStub, getStateStub);

              case 12:
                _iteratorNormalCompletion = true;
                _context.next = 8;
                break;

              case 15:
                _context.next = 21;
                break;

              case 17:
                _context.prev = 17;
                _context.t0 = _context["catch"](6);
                _didIteratorError = true;
                _iteratorError = _context.t0;

              case 21:
                _context.prev = 21;
                _context.prev = 22;

                if (!_iteratorNormalCompletion && _iterator.return != null) {
                  _iterator.return();
                }

              case 24:
                _context.prev = 24;

                if (!_didIteratorError) {
                  _context.next = 27;
                  break;
                }

                throw _iteratorError;

              case 27:
                return _context.finish(24);

              case 28:
                return _context.finish(21);

              case 29:
                (0, _chai.expect)(dispatchStub).to.have.been.calledWithMatch({
                  type: _constants.ADD_ALERT,
                  payload: {
                    message: sinon.match('item has now been viewed by a student'),
                    variant: 'error'
                  }
                });

              case 30:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, null, [[6, 17, 21, 29], [22,, 24, 28]]);
      })));
    });
  });
});