"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

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

var _chai = require("chai");

var _immutable = require("immutable");

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

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

var _stateHelper = _interopRequireWildcard(require("../stateHelper"));

var _reduxStore = require("../../../reduxStore");

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

var _Quiz = _interopRequireDefault(require("../../records/Quiz"));

var _Response = _interopRequireDefault(require("../../records/Response"));

var _SessionItem = _interopRequireDefault(require("../../records/SessionItem"));

var _SessionItemResult = _interopRequireDefault(require("../../records/SessionItemResult"));

var _QuizSession = _interopRequireDefault(require("../../records/QuizSession"));

var _QuizEntry = _interopRequireDefault(require("../../records/QuizEntry"));

var _QuizSessionEvent = _interopRequireDefault(require("../../records/QuizSessionEvent"));

var _QuizSessionResult = _interopRequireDefault(require("../../records/QuizSessionResult"));

var quizzesSelectors = _interopRequireWildcard(require("../../selectors/quizzes"));

var quizSessionsSelectors = _interopRequireWildcard(require("../../selectors/quizSessions"));

var takingSelectors = _interopRequireWildcard(require("../../selectors/taking"));

// Replacement Selectors
var deepCompareAsJSON = function deepCompareAsJSON(record1, record2) {
  var jsonRecord1 = record1;

  if (record1.toJSON) {
    jsonRecord1 = record1.toJSON();
  } else {
    // Strip funcitons and other unserializable features of the record
    jsonRecord1 = JSON.parse(JSON.stringify(record1));
  }

  var jsonRecord2 = record2;

  if (record2.toJSON) {
    jsonRecord2 = record2.toJSON();
  } else {
    // Strip funcitons and other unserializable features of the record
    jsonRecord2 = JSON.parse(JSON.stringify(record2));
  }

  (0, _chai.expect)(jsonRecord1).to.be.deep.equal(jsonRecord2);
};

describe('stateHelper and selectors', function () {
  var _allQuizSessions, _allQuizSessionEvents, _allQuizzes, _quizzes;

  var activeQuizId = '5';
  var activeQuizSessionId = '123';
  var userId = '23';
  var theActiveQuiz = {
    id: activeQuizId,
    title: 'quiz num five',
    items: ['3', '8'],
    allowBacktracking: false,
    oneAtATimeType: 'none',
    calculatorType: 'basic'
  };
  var allItems = {
    3: {
      id: '3',
      interactionType: '1',
      errors: {
        itemBody: ['Cannot be blank']
      }
    },
    4: {
      id: '4',
      interactionType: '1'
    },
    7: {
      id: '7',
      interactionType: '2'
    },
    8: {
      id: '8',
      interactionType: '2'
    }
  };
  var allQuizEntries = {
    77: new _QuizEntry.default({
      id: '77',
      quiz: activeQuizId,
      entry: (0, _immutable.Map)({
        id: '8'
      }),
      entryType: 'Item',
      position: 1
    }),
    99: new _QuizEntry.default({
      id: '99',
      quiz: activeQuizId,
      entry: (0, _immutable.Map)({
        id: '3'
      }),
      entryType: 'Item',
      position: 2
    }),
    88: new _QuizEntry.default({
      id: '88',
      quiz: '3',
      entry: (0, _immutable.Map)({
        id: '3'
      }),
      entryType: 'Item',
      position: 3
    })
  };
  var intTypes = {
    1: {
      defaultProperties: {},
      getDefaultInteractionData: function getDefaultInteractionData() {},
      getDefaultScoringData: function getDefaultScoringData() {},
      getReadableResponseText: function getReadableResponseText() {},
      getRenderedResponse: function getRenderedResponse() {},
      hideResultStem: false,
      id: '1',
      itemBody: 'Question Stem',
      isSubjective: false,
      rawName: 'Choice',
      scoringAlgorithmDefault: null,
      scoringAlgorithmOptions: [],
      slug: 'choice',
      translatedName: 'Multiple Choice',
      userResponseTypeOptions: []
    },
    2: {
      defaultProperties: {},
      getDefaultInteractionData: null,
      getDefaultScoringData: null,
      getRenderedResponse: function getRenderedResponse() {},
      getReadableResponseText: function getReadableResponseText() {},
      hideResultStem: false,
      id: '2',
      itemBody: 'Question Stem',
      isSubjective: false,
      rawName: 'True or False',
      scoringAlgorithmDefault: null,
      scoringAlgorithmOptions: [],
      slug: 't/f',
      translatedName: null,
      userResponseTypeOptions: []
    }
  };
  var allSessionItems = {
    100: {
      position: '100',
      id: '6',
      item: '3'
    },
    101: {
      position: '101',
      id: '7',
      item: '4'
    },
    102: {
      position: '102',
      id: '8',
      item: '5'
    }
  };
  var allQuizSessions = (_allQuizSessions = {
    activeQuizSessionId: activeQuizSessionId
  }, (0, _defineProperty2.default)(_allQuizSessions, activeQuizSessionId, {
    id: activeQuizSessionId,
    quiz: activeQuizId,
    sessionItems: ['100', '101'],
    sessionItemsCount: 2,
    user: {
      id: '88'
    },
    allowBacktracking: true,
    oneAtATimeType: 'question'
  }), (0, _defineProperty2.default)(_allQuizSessions, 999, {
    id: '999',
    quiz: '888',
    sessionItems: ['102'],
    user: {
      id: userId
    }
  }), (0, _defineProperty2.default)(_allQuizSessions, 111, {
    id: '111',
    quiz: '888',
    sessionItems: ['103'],
    user: {
      id: '88'
    }
  }), _allQuizSessions);
  var allQuizSessionEvents = (_allQuizSessionEvents = {}, (0, _defineProperty2.default)(_allQuizSessionEvents, activeQuizSessionId, [{
    createdAt: '2016-09-28T18:45:27.700Z|232982772',
    eventData: {
      itemId: '5',
      position: '2.0',
      userResponse: {
        value: '11'
      }
    },
    eventType: 'RESPONSE',
    quizSessionId: activeQuizSessionId
  }]), (0, _defineProperty2.default)(_allQuizSessionEvents, 992, [// <- not the active session id
  {
    createdAt: '2016-09-28T18:45:27.800Z|232982773',
    eventData: {
      itemId: '5',
      position: '1.0',
      userResponse: {
        value: '12'
      }
    },
    eventType: 'RESPONSE',
    quizSessionId: '992' // <- not the active session id

  }]), _allQuizSessionEvents);
  var allSessionItemResults = {
    1: {
      attempt: '1',
      position: '1',
      feedback: 'foo',
      score: 2
    }
  };
  var allQuizSessionResults = {
    1: {
      id: '1',
      fudgePoints: 2,
      score: '3'
    }
  };
  var allQuizzes = (_allQuizzes = {
    activeQuizId: activeQuizId
  }, (0, _defineProperty2.default)(_allQuizzes, activeQuizId, theActiveQuiz), (0, _defineProperty2.default)(_allQuizzes, 8, {
    title: 'quiz num eight',
    items: ['3', '7']
  }), _allQuizzes);
  var allTakingResponses = {
    3: {
      itemId: '1',
      position: '3',
      attempt: '1',
      userResponse: {
        value: '222'
      }
    }
  };
  var timerData = {
    timerRunning: true,
    timeLeftInSeconds: 44
  };
  var browserSessionId = 'session_id';
  var taking = {
    browserSessionId: browserSessionId,
    currentSessionItemPosition: '101',
    responses: allTakingResponses,
    quizSessionStatusOnPageLoad: _constants.IN_PROGRESS,
    timerData: timerData,
    isTaking: true
  };
  var files = [{
    file: 'file.file'
  }];
  var fakeState = (0, _immutable.fromJS)({
    editing: {
      '88_QUIZ_ENTRY_BUILD': true
    },
    interactionTypes: intTypes,
    items: allItems,
    modifications: {
      quizzes: (_quizzes = {}, (0, _defineProperty2.default)(_quizzes, activeQuizId, 'fake quiz mods for 5 (would be a map irl)'), (0, _defineProperty2.default)(_quizzes, 8, 'fake quiz mods for 8'), _quizzes),
      items: (0, _defineProperty2.default)({}, _constants.TEMPORARY_ITEM_ID, {
        id: _constants.TEMPORARY_ITEM_ID,
        itemBody: 'the temp item'
      }),
      quizEntries: (0, _defineProperty2.default)({
        77: 'fake quiz entry mods for 77'
      }, _constants.TEMPORARY_QUIZ_ENTRY_ID, {
        id: _constants.TEMPORARY_QUIZ_ENTRY_ID,
        entry: _constants.TEMPORARY_ITEM_ID,
        position: 23
      })
    },
    quizSessionEvents: allQuizSessionEvents,
    quizSessionResults: allQuizSessionResults,
    quizSessions: allQuizSessions,
    quizzes: allQuizzes,
    quizEntries: allQuizEntries,
    sessionItemResults: allSessionItemResults,
    sessionItems: allSessionItems,
    sidebar: {
      isOpen: false
    },
    taking: taking,
    upload: {
      files: files
    }
  });
  beforeEach(function () {
    (0, _reduxStore.setFakeStore)(fakeState);
  });
  afterEach(function () {
    (0, _reduxStore.unsetFakeStore)();
  });
  it('returns the activeQuizId', function () {
    (0, _chai.expect)(quizzesSelectors.getActiveQuizId(fakeState)).to.be.equal(activeQuizId);
  });
  it('returns the activeQuizSessionId', function () {
    (0, _chai.expect)(quizSessionsSelectors.getActiveQuizSessionId(fakeState)).to.be.equal(activeQuizSessionId);
  });
  it('returns the right activeQuiz', function () {
    var expected = new _Quiz.default(theActiveQuiz);
    deepCompareAsJSON(_stateHelper.default.activeQuiz(), expected);
  });
  it('returns all of the interactionTypes', function () {
    (0, _chai.expect)(_stateHelper.default.interactionTypes().toJS()).to.be.deep.equal(Object.values(intTypes));
  });
  describe('activeQuizSession', function () {
    it('finds the current QuizSession', function () {
      var expected = new _QuizSession.default(allQuizSessions[activeQuizSessionId]);
      deepCompareAsJSON(_stateHelper.default.activeQuizSession(), expected);
    });
  });

  var findTest = function findTest(ClassString, RecordClass, recordsMap, existingId) {
    it("finds an existing ".concat(ClassString), function () {
      var expected = new RecordClass(recordsMap[existingId]);
      deepCompareAsJSON(_stateHelper.default["find".concat(ClassString)](existingId), expected);
    });
  };

  var findDefaultTest = function findDefaultTest(ClassString, RecordClass) {
    it("returns a default ".concat(ClassString, " if none found"), function () {
      var defaultRecordOfType = new RecordClass();
      var keyNotInState = 'this_should_not_be_found';
      deepCompareAsJSON(_stateHelper.default["find".concat(ClassString)](keyNotInState), defaultRecordOfType);
    });
  };

  describe('findQuiz', function () {
    findTest('Quiz', _Quiz.default, allQuizzes, activeQuizId);
    findDefaultTest('Quiz', _Quiz.default);
  });
  describe('findItem', function () {
    findTest('Item', _Item.default, allItems, '3');
    findDefaultTest('Item', _Item.default);
    it('returns the temporary item if ID matches', function () {
      var tempItem = _stateHelper.default.findItem(_constants.TEMPORARY_ITEM_ID);

      (0, _chai.expect)(tempItem.itemBody).to.be.equal('the temp item');
    });
  });
  describe('findQuizEntry', function () {
    findTest('QuizEntry', _QuizEntry.default, allQuizEntries, '77');
    findDefaultTest('QuizEntry', _QuizEntry.default);
    it('returns the temporary quiz entry if ID matches', function () {
      var tempQuizEntry = _stateHelper.default.findQuizEntry(_constants.TEMPORARY_QUIZ_ENTRY_ID);

      (0, _chai.expect)(tempQuizEntry.position).to.be.equal(23);
      (0, _chai.expect)(tempQuizEntry.entry).to.be.equal(_constants.TEMPORARY_ITEM_ID);
    });
  });
  describe('findQuizSession', function () {
    findTest('QuizSession', _QuizSession.default, allQuizSessions, '123');
    findDefaultTest('QuizSession', _QuizSession.default);
  });
  describe('findTakingResponse', function () {
    findTest('TakingResponse', _Response.default, allTakingResponses, '3');
    findDefaultTest('TakingResponse', _Response.default);
  });
  describe('findInteractionType', function () {
    findTest('InteractionType', _InteractionType.default, intTypes, '1');
    findDefaultTest('InteractionType', _InteractionType.default);
  });
  describe('findSessionItem', function () {
    findTest('SessionItem', _SessionItem.default, allSessionItems, '101');
    findDefaultTest('SessionItem', _SessionItem.default);
  });
  describe('findSessionItemResult', function () {
    findTest('SessionItemResult', _SessionItemResult.default, allSessionItemResults, '1');
    findDefaultTest('SessionItemResult', _SessionItemResult.default);
  });
  describe('findQuizSessionResult', function () {
    findTest('QuizSessionResult', _QuizSessionResult.default, allQuizSessionResults, '1');
    findDefaultTest('QuizSessionResult', _QuizSessionResult.default);
  });
  describe('findQuizSessionEvent', function () {
    findTest('QuizSessionEvent', _QuizSessionEvent.default, allSessionItemResults, activeQuizSessionId);
    findDefaultTest('QuizSessionEvent', _QuizSessionEvent.default);
  });
  describe('getSessionId', function () {
    it('returns the proper quiz sesison id', function () {
      (0, _chai.expect)(takingSelectors.getBrowserSessionId(fakeState)).to.eql(browserSessionId);
    });
  });
  describe('getTimerData', function () {
    it('returns the proper timer data', function () {
      (0, _chai.expect)(takingSelectors.getTimerData(fakeState).toJS()).to.eql(timerData);
    });
  });
  describe('getIsTaking', function () {
    it('returns isTaking', function () {
      (0, _chai.expect)(takingSelectors.getIsTaking(fakeState)).to.eql(taking.isTaking);
    });
  });
  describe('getResponseByPosition', function () {
    it('returns the correct response', function () {
      var resp = allTakingResponses['3'];
      (0, _chai.expect)(takingSelectors.getResponseByPosition(fakeState, resp.position).toJS()).to.eql(resp);
    });
    it('returns an empty map if no response is found', function () {
      (0, _chai.expect)(takingSelectors.getResponseByPosition(fakeState, '3000').toJS()).to.eql({});
    });
  });
  describe('getCurrentSessionItemPosition', function () {
    it('returns the current session item position', function () {
      (0, _chai.expect)(takingSelectors.getCurrentSessionItemPosition(fakeState)).to.eql('101');
    });
  });
  describe('getSessionItemsCount', function () {
    it('returns the session items count', function () {// Add this one in!
      // expect(quizSessionsSelectors.getSessionItemsCount()).to.eql(2)
    });
  });
  describe('backtrackingIsAllowed', function () {
    it('returns whether backtracking is allowed', function () {
      (0, _chai.expect)(quizSessionsSelectors.getBacktrackingIsAllowed(fakeState)).to.eql(true);
    });
  });
  describe('isOneQuestionAtATime', function () {
    it('returns whether it is one question at a time', function () {
      (0, _chai.expect)(quizSessionsSelectors.isOneQuestionAtATime(fakeState)).to.eql(true);
    });
  });
  describe('calculatorType', function () {
    it('returns the calculator type', function () {
      (0, _chai.expect)(quizzesSelectors.getActiveQuizCaluclatorType(fakeState)).to.eql('basic');
    });
  });
  describe('findQuizSessions', function () {
    it('returns an empty collection without ids', function () {
      var _stateHelper$findQuiz = _stateHelper.default.findQuizSessions(),
          size = _stateHelper$findQuiz.size;

      (0, _chai.expect)(size).to.eq(0);
    });
    it('returns the requested quizSessions for ids', function () {
      var list = _stateHelper.default.findQuizSessions(['111', '999']);

      var ids = list.map(function (qs) {
        return qs.get('id');
      }).toJS();
      (0, _chai.expect)(list.first()).to.be.an.instanceof(_QuizSession.default);
      (0, _chai.expect)(ids).to.deep.eq(['111', '999']);
    });
  });
  describe('quizEntryWithErrorsShowing', function () {
    it('returns the invalid quizEntry', function () {
      (0, _chai.expect)(_stateHelper.default.quizEntryWithErrorsShowing().position).to.eq(3);
    });
  });
  describe('editingQuizEntry', function () {
    it('returns true when editing a quizEntry', function () {
      (0, _chai.expect)(_stateHelper.default.editingQuizEntry()).to.be.true();
    });
    it('returns false when not editing a quizEntry', function () {
      (0, _reduxStore.setFakeStore)((0, _immutable.fromJS)({
        editing: {
          '88_QUIZ_ENTRY_BUILD': false,
          somethingElse: true
        }
      }));
      (0, _chai.expect)(_stateHelper.default.editingQuizEntry() || false).to.be.false();
    });
  });
});
describe('timeIsUp', function () {
  context('context timerRunning false', function () {
    it('returns the proper timer data', function () {
      var fakeState = (0, _immutable.fromJS)({
        taking: {
          timerData: {
            timerRunning: false,
            timeLeftInSeconds: -10
          }
        }
      });
      (0, _stateHelper.timeIsUp)(fakeState);
      (0, _chai.expect)((0, _stateHelper.timeIsUp)(fakeState)).to.eql(false);
    });
  });
  context('context timerRunning', function () {
    it('returns true if time is at zero', function () {
      var fakeState = (0, _immutable.fromJS)({
        taking: {
          timerData: {
            timerRunning: true,
            timeLeftInSeconds: 0
          }
        }
      });
      (0, _stateHelper.timeIsUp)(fakeState);
      (0, _chai.expect)((0, _stateHelper.timeIsUp)(fakeState)).to.eql(true);
    });
    it('returns true if time is less than', function () {
      var fakeState = (0, _immutable.fromJS)({
        taking: {
          timerData: {
            timerRunning: true,
            timeLeftInSeconds: -10
          }
        }
      });
      (0, _stateHelper.timeIsUp)(fakeState);
      (0, _chai.expect)((0, _stateHelper.timeIsUp)(fakeState)).to.eql(true);
    });
    it('returns false if time is positive', function () {
      var fakeState = (0, _immutable.fromJS)({
        taking: {
          timerData: {
            timerRunning: true,
            timeLeftInSeconds: 10
          }
        }
      });
      (0, _stateHelper.timeIsUp)(fakeState);
      (0, _chai.expect)((0, _stateHelper.timeIsUp)(fakeState)).to.eql(false);
    });
  });
});