"use strict";

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

var _humps = require("humps");

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

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

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

var _upload = require("../../../common/actions/upload");

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

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

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

var _qtiImports2 = require("../../../common/actions/qtiImports");

describe('qti import api action creators', function () {
  var dispatchStub = sinon.stub();
  var getStateStub = sinon.stub();
  var fetchStub = sinon.stub();
  var quizId = '2';
  var bankId = '5';
  useFakeFetching({
    dispatchStub: dispatchStub,
    getStateStub: getStateStub,
    fetchStub: fetchStub
  });
  describe('getQTIInfo', function () {
    var getQTIImportsThunk = (0, _qtiImports.getQTIInfo)(quizId);
    it('gets the correct url', function () {
      getQTIImportsThunk(dispatchStub, getStateStub);
      fetchStub.calledWith("/api/quizzes/".concat(quizId, "/qti_imports"));
    });
    it('tries to persist the response data to the store', function (done) {
      var qtiResponseData = [{
        id: 1,
        parent_id: 2,
        parent_type: 'Quiz',
        status: 'failed'
      }, {
        id: 3,
        parent_id: 2,
        parent_type: 'Quiz',
        status: 'started'
      }];
      var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
      _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
      var fetchPromise = getQTIImportsThunk(dispatchStub, getStateStub);
      var parsedImportData = [{
        id: 1,
        parentId: 2,
        parentType: 'Quiz',
        status: 'failed'
      }, {
        id: 3,
        parentId: 2,
        parentType: 'Quiz',
        status: 'started'
      }];
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)(parsedImportData));
        done();
      });
    });
  });
  describe('pollForQtiInfo', function () {
    var clock = null;
    beforeEach(function () {
      clock = sinon.useFakeTimers();
    });
    afterEach(function () {
      clock.restore();
      getQuizAndItemsStub.resetHistory();
    });
    var getQuizAndItemsStub = sinon.stub();
    var getBankAndEntriesStub = sinon.stub();
    var pollingStub = sinon.stub();
    var pollForQtiInfoThunk = (0, _qtiImports.pollForQtiInfo)(quizId, _constants.PARENT_TYPE_QUIZ, {
      getExistingQuizAndItems: getQuizAndItemsStub,
      pollForQtiInfo: pollingStub
    });
    var pollForBankQtiInfoThunk = (0, _qtiImports.pollForQtiInfo)(bankId, _constants.PARENT_TYPE_BANK, {
      getExistingBankAndEntries: getBankAndEntriesStub,
      pollForQtiInfo: pollingStub
    });
    it('gets the correct url', function () {
      pollForQtiInfoThunk(dispatchStub, getStateStub);
      fetchStub.calledWith("/api/quizzes/".concat(quizId, "/qti_imports"));
    });
    it('gets the correct url for bank', function () {
      pollForBankQtiInfoThunk(dispatchStub, getStateStub);
      fetchStub.calledWith("/api/banks/".concat(bankId, "/qti_imports"));
    });
    it('persists the response data to the store and triggers the next loop', function (done) {
      var qtiResponseData = [{
        id: 1,
        parent_id: 2,
        parent_type: 'Quiz',
        status: 'scheduled'
      }, {
        id: 3,
        parent_id: 2,
        parent_type: 'Quiz',
        status: 'importing'
      }];
      var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
      _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
      var fetchPromise = pollForQtiInfoThunk(dispatchStub, getStateStub);
      clock.tick(2500);
      fetchPromise.then(function () {
        checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)((0, _humps.camelizeKeys)(qtiResponseData)));
        expect(pollingStub.called).to.be.true();
        done();
      });
    });
    context('on import success', function () {
      it('persists the response data to the store and triggers the next quiz reload when done', function (done) {
        var qtiResponseData = [{
          id: 1,
          parent_id: 2,
          parent_type: 'Quiz',
          status: 'scheduled'
        }, {
          id: 3,
          parent_id: 2,
          parent_type: 'Quiz',
          status: 'completed'
        }];
        var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
        _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
        var fetchPromise = pollForQtiInfoThunk(dispatchStub, getStateStub);
        clock.tick(2500);
        fetchPromise.then(function () {
          checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)((0, _humps.camelizeKeys)(qtiResponseData)));
          checkActionDispatched(dispatchStub, (0, _upload.uploadStatus)(_constants.FILE_UPLOAD_SUCCESS));
          expect(getQuizAndItemsStub.called).to.be.true();
          done();
        });
      });
      context('on bank import success', function () {
        it('persists the response data to the store and triggers the next bank reload when done', function (done) {
          var qtiResponseData = [{
            id: 1,
            parent_id: 2,
            parent_type: 'Bank',
            status: 'scheduled'
          }, {
            id: 3,
            parent_id: 2,
            parent_type: 'Bank',
            status: 'completed'
          }];
          var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
          _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
          var fetchPromise = pollForBankQtiInfoThunk(dispatchStub, getStateStub);
          clock.tick(2500);
          fetchPromise.then(function () {
            checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)((0, _humps.camelizeKeys)(qtiResponseData)));
            checkActionDispatched(dispatchStub, (0, _upload.uploadStatus)(_constants.FILE_UPLOAD_SUCCESS));
            expect(getBankAndEntriesStub.called).to.be.true();
            done();
          });
        });
      });
    });
    context('on import failure', function () {
      it('persists the response data to the store and stops loop', function (done) {
        var qtiResponseData = [{
          id: 1,
          parent_id: 2,
          parent_type: 'Quiz',
          status: 'failed'
        }];
        var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
        _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
        var fetchPromise = pollForQtiInfoThunk(dispatchStub, getStateStub);
        clock.tick(2500);
        fetchPromise.then(function () {
          checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)((0, _humps.camelizeKeys)(qtiResponseData)));
          checkActionDispatched(dispatchStub, (0, _upload.uploadStatus)(_constants.FILE_UPLOAD_FAILURE));
          expect(getQuizAndItemsStub.called).to.not.be.true();
          done();
        });
      });
      it('will not block future imports from polling', function (done) {
        var qtiResponseData = [{
          id: 1,
          parent_id: 2,
          parent_type: 'Quiz',
          status: 'failed'
        }, {
          id: 3,
          parent_id: 2,
          parent_type: 'Quiz',
          status: 'importing'
        }];
        var response = (0, _jsonify.jsoniblePromise)(qtiResponseData);
        _Fetcher.default.fakeFetch = (0, _fakeFetch.default)(response);
        var fetchPromise = pollForBankQtiInfoThunk(dispatchStub, getStateStub);
        clock.tick(2500);
        fetchPromise.then(function () {
          checkActionDispatched(dispatchStub, (0, _qtiImports2.addQtiImports)((0, _humps.camelizeKeys)(qtiResponseData)));
          expect(pollingStub.called).to.be.true();
          done();
        });
      });
    });
  });
  describe('upload actions', function () {
    var quizId = '22';
    var bankId = '32';
    var fakeS3Url = 'http://s3/fake/url';
    var uploadUrlResponse = {
      url: fakeS3Url
    };
    var file = {
      type: 'filetype',
      name: 'BLOB'
    };
    var errorResponse = (0, _jsonify.jsoniblePromise)({
      status: 500
    });
    var fakeErrorFetch = (0, _fakeFetch.default)(errorResponse);
    var emptyResponse = (0, _jsonify.jsoniblePromise)({});
    var fakeEmptyFetch = (0, _fakeFetch.default)(emptyResponse);
    var onErrorStub = sinon.stub();
    var s3UploadFetchStub = sinon.stub();
    var postQtiCreateStub = sinon.stub();
    var dispatchStub = sinon.stub();
    var getStateStub = sinon.stub();
    var fetchStub = sinon.stub();
    useFakeFetching({
      dispatchStub: dispatchStub,
      getStateStub: getStateStub,
      fetchStub: fetchStub
    });
    afterEach(function () {
      onErrorStub.resetHistory();
      s3UploadFetchStub.resetHistory();
      postQtiCreateStub.resetHistory();
    });
    describe('postQtiCreate', function () {
      var fakePostURL = 'api/quizzes/22/qti_imports';

      var stubbedPostQtiCreateCall = function stubbedPostQtiCreateCall() {
        var postQtiCreateWithUrl = (0, _qtiImports.postQtiCreate)(fakePostURL);
        var postQtiCreateThunk = postQtiCreateWithUrl(fakeS3Url, dispatchStub, getStateStub);
        return postQtiCreateThunk;
      };

      var fakePostBankURL = 'api/banks/32/qti_imports';

      var stubbedPostQtiCreateBankCall = function stubbedPostQtiCreateBankCall() {
        var postQtiCreateWithUrl = (0, _qtiImports.postQtiCreate)(fakePostBankURL);
        var postQtiCreateThunk = postQtiCreateWithUrl(fakeS3Url, dispatchStub, getStateStub);
        return postQtiCreateThunk;
      };

      it('should mark the file upload url fetch call as started', function () {
        stubbedPostQtiCreateCall();
        checkActionDispatched(dispatchStub, (0, _callHelpers.startCallFor)(_constants.CREATE_QTI_IMPORT));
      });
      it('should upload to the provided url', function () {
        stubbedPostQtiCreateCall();
        expect(fetchStub.calledWith(fakePostURL)).to.be.true();
      });
      it('should upload to the provided url for bank', function () {
        stubbedPostQtiCreateBankCall();
        expect(fetchStub.calledWith(fakePostBankURL)).to.be.true();
      });

      var fakePostQtiCreate = function fakePostQtiCreate() {
        _Fetcher.default.fakeFetch = fakeEmptyFetch;
        var postQtiCreateWithUrl = (0, _qtiImports.postQtiCreate)(fakePostURL, dispatchStub);
        var postQtiCreateThunk = postQtiCreateWithUrl(fakeS3Url, dispatchStub, getStateStub);
        return postQtiCreateThunk;
      };

      it('should mark the create call as a success on return', function (done) {
        fakePostQtiCreate().then(function () {
          checkActionDispatched(dispatchStub, (0, _callHelpers.successCallFor)(_constants.CREATE_QTI_IMPORT));
          done();
        });
      });
      context('error on creating the qti import', function () {
        beforeEach(function () {
          _Fetcher.default.fakeFetch = fakeErrorFetch;
        });
        it('should call the onError callback', function (done) {
          fakePostQtiCreate().then(done());
          expect(onErrorStub.called).to.be.true();
        });
      });
    });
    describe('qtiFileUpload', function () {
      var fakeUploadFile = function fakeUploadFile() {
        var uploadFileThunk = (0, _qtiImports.qtiFileUpload)(file, quizId, _constants.PARENT_TYPE_QUIZ, onErrorStub, s3UploadFetchStub, postQtiCreateStub);
        return uploadFileThunk(dispatchStub, getStateStub);
      };

      var fakeUploadBankFile = function fakeUploadBankFile() {
        var uploadFileThunk = (0, _qtiImports.qtiFileUpload)(file, bankId, _constants.PARENT_TYPE_BANK, onErrorStub, s3UploadFetchStub, postQtiCreateStub);
        return uploadFileThunk(dispatchStub, getStateStub);
      };

      it('should mark the file upload url fetch call as started', function () {
        fakeUploadFile();
        checkActionDispatched(dispatchStub, (0, _callHelpers.startCallFor)(_constants.FILE_UPLOAD_URL_CALL));
      });
      it('should hit the right upload_url endpoint', function () {
        fakeUploadFile();
        expect(fetchStub.calledWith('/api/quizzes/22/qti_imports/upload_url')).to.be.true();
      });
      it('should hit the right upload_url endpoint for bank', function () {
        fakeUploadBankFile();
        expect(fetchStub.calledWith('/api/banks/32/qti_imports/upload_url')).to.be.true();
      });
      it('should mark the create call as a success on return', function (done) {
        var response = (0, _jsonify.jsoniblePromise)(uploadUrlResponse);
        var fakeUrlFetch = (0, _fakeFetch.default)(response);
        _Fetcher.default.fakeFetch = fakeUrlFetch;
        fakeUploadFile().then(function () {
          checkActionDispatched(dispatchStub, (0, _callHelpers.successCallFor)(_constants.FILE_UPLOAD_URL_CALL));
          done();
        });
      });
      it('passes the error callback to fileUploadFxn', function () {
        fakeUploadFile();
        expect(s3UploadFetchStub.getCall(0).args[2]).to.eq(onErrorStub);
      });
      it('passes the error callback to qtiCreateFxn', function () {
        fakeUploadFile();
        expect(postQtiCreateStub.getCall(0).args[2]).to.eq(onErrorStub);
      });
      context('error on getting the qti import upload url', function () {
        beforeEach(function () {
          _Fetcher.default.fakeFetch = fakeErrorFetch;
        });
        it('should call the onError callback', function (done) {
          fakeUploadFile().then(done());
          expect(onErrorStub.called).to.be.true();
        });
      });
    });
  });
});