"use strict";

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

var _immutable = require("immutable");

var _chai = require("chai");

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

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

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

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

var _quizzes2 = require("../quizzes");

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

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

var _checkActionDispatched = _interopRequireDefault(require("../../../../tests/util/checkActionDispatched"));

var _httpHeaders = require("../../../common/util/httpHeaders");

describe('quizzes api action creators', function () {
  var fetchStub = sinon.stub().returns(new Promise(function (resolve) {
    return resolve;
  }));
  var dispatchStub = sinon.stub();
  var getStateStub = sinon.stub();
  useFakeFetching({
    dispatchStub: dispatchStub,
    getStateStub: getStateStub,
    fetchStub: fetchStub
  });

  var fakeRecord = function fakeRecord(data) {
    var r = (0, _immutable.fromJS)(data);

    r.validData = function () {
      return r;
    };

    return r;
  };

  describe('saveQuizChange', function () {
    it('does nothing if workingQuiz is the same as quiz', function () {
      var sameThing = fakeRecord({});
      var saveQuizAction = (0, _quizzes2.saveQuizChange)(sameThing, sameThing);
      (0, _chai.expect)(saveQuizAction.type).to.be.equal(_constants.DO_NOTHING);
    });

    var stubbedQuizModCall = function stubbedQuizModCall(quizId) {
      var quiz = fakeRecord({
        id: quizId
      });
      var quizMod = fakeRecord({
        id: quizId,
        title: 'title mod'
      });
      var saveQuizThunk = (0, _quizzes2.saveQuizChange)(quiz, quizMod);
      saveQuizThunk(dispatchStub, getStateStub);
    };

    it('marks that the quiz is saving', function () {
      stubbedQuizModCall('12');
      var savingAction = (0, _callHelpers.startCallFor)(_constants.QUIZ_SAVE_CALL);
      (0, _checkActionDispatched.default)(dispatchStub, savingAction);
    });
    it('puts to the right endpoint', function () {
      stubbedQuizModCall('22');
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes/22')).to.be.true();
    });

    var fakeQuizModCall = function fakeQuizModCall(mockQuizMods) {
      var quiz = fakeRecord({
        id: '22'
      });
      var quizMod = fakeRecord(mockQuizMods);
      var response = (0, _jsonify.jsoniblePromise)(mockQuizMods);
      var fakeFetch = (0, _fakeFetch.default)(response);
      _Fetcher.default.fakeFetch = fakeFetch;
      var saveQuizThunk = (0, _quizzes2.saveQuizChange)(quiz, quizMod);
      var fetchPromise = saveQuizThunk(dispatchStub, getStateStub);
      return fetchPromise;
    };

    it('marks that the quiz saving as done in the cb', function (done) {
      var mockQuizMods = {
        id: '22',
        title: 'title mod'
      };
      var fetchPromise = fakeQuizModCall(mockQuizMods);
      var endSaveAction = (0, _callHelpers.successCallFor)(_constants.QUIZ_SAVE_CALL);
      fetchPromise.then(function () {
        (0, _checkActionDispatched.default)(dispatchStub, endSaveAction);
        done();
      });
    });
    it('tries to persist the change in the cb with addQuizzes action', function (done) {
      var mockQuizMods = {
        id: '22',
        title: 'title mod'
      };
      var fetchPromise = fakeQuizModCall(mockQuizMods);
      var expectedAction = (0, _quizzes.addQuizzes)([mockQuizMods]);
      fetchPromise.then(function () {
        (0, _checkActionDispatched.default)(dispatchStub, expectedAction);
        done();
      });
    });
  });
  describe('startNewQuiz', function () {
    var stubbedNewQuizCall = function stubbedNewQuizCall() {
      var startNewQuizThunk = (0, _quizzes2.startNewQuiz)();
      startNewQuizThunk(dispatchStub, getStateStub);
    };

    it('posts to the right endpoint', function () {
      stubbedNewQuizCall();
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes')).to.be.true();
    });

    var fakeNewQuizCall = function fakeNewQuizCall(quizInfo) {
      var response = (0, _jsonify.jsoniblePromise)(quizInfo);
      var fakeFetch = (0, _fakeFetch.default)(response);
      _Fetcher.default.fakeFetch = fakeFetch;
      var newQuizThunk = (0, _quizzes2.startNewQuiz)();
      var fetchPromise = newQuizThunk(dispatchStub, getStateStub);
      return fetchPromise;
    };

    it('adds a new active quiz id', function (done) {
      var quizInfo = {
        id: '28'
      };
      var fetchPromise = fakeNewQuizCall(quizInfo);
      var newActiveQuizAction = (0, _quizzes.newActiveQuiz)('28');
      fetchPromise.then(function () {
        (0, _checkActionDispatched.default)(dispatchStub, newActiveQuizAction);
        done();
      });
    });
  });
  describe('getExistingQuizAndItemsForBuilding', function () {
    var stubbedGetQuizCall = function stubbedGetQuizCall() {
      var quizId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '8';
      var getExistingQuizThunk = (0, _quizzes2.getExistingQuizAndItemsForBuilding)(quizId);
      getExistingQuizThunk(dispatchStub, getStateStub);
    };

    it('gets from the right endpoint with the correct httpHeaders and method', function () {
      var getParams = {
        method: 'GET',
        headers: (0, _httpHeaders.httpHeaders)('fakeusertoken')
      };
      stubbedGetQuizCall('10');
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes/10', getParams)).to.be.true();
    });

    var fakeGetQuizCall = function fakeGetQuizCall(quizInfo) {
      var response = (0, _jsonify.jsoniblePromise)(quizInfo || {
        id: '22'
      });
      var fakeFetch = (0, _fakeFetch.default)(response);
      _Fetcher.default.fakeFetch = fakeFetch;
      var getExistingQuizThunk = (0, _quizzes2.getExistingQuizAndItemsForBuilding)('22');
      var fetchPromise = getExistingQuizThunk(dispatchStub, getStateStub);
      return fetchPromise;
    };

    context('with qti import', function () {
      it('calls a qti_import retrieval', function (done) {
        var quizInfo = {
          id: '28'
        };
        var fetchPromise = fakeGetQuizCall(quizInfo);
        fetchPromise.then(function () {
          fetchStub.calledWith('/api/quizzes/28/qti_imports');
          done();
        });
      });
    });
  });
  describe('quizBuildingSession', function () {
    it('fetches the quiz', function () {
      var getStateStub = sinon.stub().returns((0, _immutable.fromJS)({
        quizzes: {
          activeQuizId: '1',
          28: {
            id: '28'
          }
        }
      }));
      var routerParams = {
        contextId: '2',
        activeQuizId: '28'
      };
      (0, _quizzes2.quizBuildingSession)(routerParams)(dispatchStub, getStateStub);
      var fetchQuizAction = dispatchStub.firstCall.args[0];
      (0, _chai.expect)(fetchQuizAction).to.be.a('function');
      fetchQuizAction(dispatchStub, getStateStub);
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes/28')).to.be.true();
    });
    it('starts new quiz if needed', function () {
      var getStateStub = sinon.stub().returns((0, _immutable.fromJS)({
        quizzes: {
          activeQuizId: '28',
          28: {
            id: '28'
          }
        }
      }));
      var routerParams = {
        contextId: '2',
        createNew: true
      };
      (0, _quizzes2.quizBuildingSession)(routerParams)(dispatchStub, getStateStub);
      var newQuizAction = dispatchStub.firstCall.args[0];
      (0, _chai.expect)(newQuizAction).to.be.a('function');
      newQuizAction(dispatchStub, getStateStub);
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes')).to.be.true();
    });
    it('does nothing if quiz and questions are loaded', function () {
      var getStateStub = sinon.stub().returns((0, _immutable.fromJS)({
        quizzes: {
          activeQuizId: '3',
          28: {
            id: '28'
          }
        },
        quizEntries: {
          1: {},
          2: {}
        }
      }));
      var routerParams = {
        contextId: '2',
        createNew: true,
        activeQuizId: '3'
      };
      var noopAction = (0, _quizzes2.quizBuildingSession)(routerParams)(dispatchStub, getStateStub);
      (0, _chai.expect)(noopAction).to.deep.equal({
        type: _constants.DO_NOTHING
      });
    });
  });

  var setUpSetQuizPropertyAssertion = function setUpSetQuizPropertyAssertion(quizSetPropertyFunc) {
    var getStateStub = sinon.stub().returns((0, _immutable.fromJS)({
      quizzes: {}
    }));
    useFakeFetching({
      dispatchStub: dispatchStub,
      getStateStub: getStateStub,
      fetchStub: fetchStub
    });
    var quizId = '123';

    var stubbedCall = function stubbedCall(value) {
      _Fetcher.default.fakeFetch = fetchStub;
      quizSetPropertyFunc(quizId, value)(dispatchStub, getStateStub);
    };

    return function (value, expectedPayload) {
      stubbedCall(value);
      (0, _chai.expect)(fetchStub.calledWithMatch("/api/quizzes/".concat(quizId), {
        method: 'PATCH',
        body: JSON.stringify({
          id: quizId,
          quiz: expectedPayload
        })
      })).to.be.true();
    };
  };

  describe('#setBacktracking', function () {
    var assertBacktracking = setUpSetQuizPropertyAssertion(_quizzes2.setBacktracking);
    it('should send allow_backtracking with truthy value', function () {
      assertBacktracking(1, {
        allow_backtracking: true
      });
    });
  });
  describe('#setCalculatorType', function () {
    var assertCalculatorType = setUpSetQuizPropertyAssertion(_quizzes2.setCalculatorType);
    it('should send calculator_type with value \'none\'', function () {
      assertCalculatorType('none', {
        calculator_type: 'none'
      });
    });
  });
  describe('#setOneAtATimeType', function () {
    var assertOQAAT = setUpSetQuizPropertyAssertion(_quizzes2.setOneAtATimeType);
    it('should send one_at_a_time_type with value \'question\' if passed truthy value', function () {
      assertOQAAT(true, {
        one_at_a_time_type: 'question'
      });
    });
    it('should send one_at_a_time_type null if passed falsey value', function () {
      assertOQAAT(false, {
        one_at_a_time_type: null
      });
    });
  });
  describe('#setQuizShuffleQuestions', function () {
    var setQuizShuffleQuestionsAssertion = setUpSetQuizPropertyAssertion(_quizzes2.setQuizShuffleQuestions);
    it('should send shuffle_questions with truthy value', function () {
      setQuizShuffleQuestionsAssertion(1, {
        shuffle_questions: true
      });
    });
    it('should send shuffle_questions with falsy value', function () {
      setQuizShuffleQuestionsAssertion(false, {
        shuffle_questions: false
      });
    });
  });
  describe('#setQuizHasTimeLimit', function () {
    var setQuizHasTimeLimitAssertion = setUpSetQuizPropertyAssertion(_quizzes2.setQuizHasTimeLimit);
    it('should send has_time_limit with truthy value', function () {
      setQuizHasTimeLimitAssertion(1, {
        has_time_limit: true
      });
    });
    it('should send has_time_limit with falsy value', function () {
      setQuizHasTimeLimitAssertion(false, {
        has_time_limit: false
      });
    });
  });
  describe('#setSessionTimeLimitInSecondsApi', function () {
    var setSessionTimeLimitAssertion = setUpSetQuizPropertyAssertion(_quizzes2.setSessionTimeLimitInSecondsApi);
    it('should send session_time_limit_in_seconds with integer value', function () {
      setSessionTimeLimitAssertion(1, {
        session_time_limit_in_seconds: 1
      });
    });
  });
  describe('#setSessionTimeLimitInSecondsUi', function () {
    it('dispatches the correct action and payload', function () {
      var thunk = (0, _quizzes2.setSessionTimeLimitInSecondsUi)(1, 3600);
      thunk(dispatchStub);
      (0, _chai.expect)(dispatchStub.firstCall.args[0]).to.deep.eq({
        payload: {
          id: 1,
          modifications: {
            sessionTimeLimitInSeconds: 3600
          }
        },
        type: 'QUIZ_MODIFICATION'
      });
    });
  });
  describe('#interactionFileUpload', function () {
    var parentId = '22';

    var onSuccess = function onSuccess() {};

    var onError = function onError() {};

    var withUrlCallback = sinon.stub();

    var fakeInteractionUpload = function fakeInteractionUpload(parentType) {
      var uploadFileThunk = (0, _quizzes2.interactionFileUpload)(parentType, parentId, 'some file', onSuccess, onError, null, withUrlCallback);
      return uploadFileThunk(dispatchStub, getStateStub);
    };

    afterEach(function () {
      withUrlCallback.resetHistory();
    });
    it('calls to the banks url if parentType is bank', function () {
      fakeInteractionUpload(_constants.PARENT_TYPE_BANK);
      (0, _chai.expect)(fetchStub.calledWith('/api/banks/22/items/media_upload_url')).to.be.true();
    });
    it('calls to the quizzes url if parentType is quiz', function () {
      fakeInteractionUpload(_constants.PARENT_TYPE_QUIZ);
      (0, _chai.expect)(fetchStub.calledWith('/api/quizzes/22/items/media_upload_url')).to.be.true();
    });
  });
  describe('#setFilterIpAddress', function () {
    var assertFilterIpAddress = setUpSetQuizPropertyAssertion(_quizzes2.setFilterIpAddress);
    it('should send filter_ip_address to false', function () {
      assertFilterIpAddress(false, {
        filter_ip_address: false
      });
    });
    it('should send filter_ip_address to true', function () {
      assertFilterIpAddress(true, {
        filter_ip_address: true
      });
    });
  });
  describe('#setIpFiltersApi', function () {
    var assertSetIpFiltersApi = setUpSetQuizPropertyAssertion(_quizzes2.setIpFiltersApi);
    it('should set filters[ips] to an empty array', function () {
      assertSetIpFiltersApi([], {
        filters: {
          ips: []
        }
      });
    });
    it('should set filters[ips] to an array with empty strings', function () {
      assertSetIpFiltersApi([['', '']], {
        filters: {
          ips: [['', '']]
        }
      });
    });
    it('should set filters[ips] to an array with valid ips', function () {
      assertSetIpFiltersApi([['1.1.1.1', '9.9.9.9']], {
        filters: {
          ips: [['1.1.1.1', '9.9.9.9']]
        }
      });
    });
    it('should set filters[ips] to an array with many valid ips', function () {
      assertSetIpFiltersApi([['1.1.1.1', '9.9.9.9'], ['100.100.100.100', '200.200.200.200']], {
        filters: {
          ips: [['1.1.1.1', '9.9.9.9'], ['100.100.100.100', '200.200.200.200']]
        }
      });
    });
  });
  describe('#setIpFiltersUi', function () {
    it('dispatches the correct action and payload', function () {
      var thunk = (0, _quizzes2.setIpFiltersUi)(1, [['0.0.0.0', '255.255.255.255']]);
      thunk(dispatchStub);
      (0, _chai.expect)(dispatchStub.firstCall.args[0]).to.deep.eq({
        type: 'QUIZ_MODIFICATION',
        payload: {
          id: 1,
          modifications: {
            filters: {
              ips: [['0.0.0.0', '255.255.255.255']]
            }
          }
        }
      });
    });
  });
});