"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _immutable = require("immutable");

var _isArrayLike = _interopRequireDefault(require("lodash/isArrayLike"));

var _keyBy = _interopRequireDefault(require("lodash/keyBy"));

var _map = _interopRequireDefault(require("lodash/map"));

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

var assocQuizEntry = function assocQuizEntry(state, quizId, quizEntries) {
  var quizEntryIds = (0, _immutable.List)((0, _map.default)(quizEntries, 'id'));
  return state.setIn([quizId, 'quizEntries'], quizEntryIds);
};

var dissocQuizEntry = function dissocQuizEntry(state, quizId, quizEntryId) {
  return state.updateIn([quizId, 'quizEntries'], function (quizEntriesList) {
    return quizEntriesList.filter(function (item) {
      return item !== quizEntryId;
    });
  });
};

var assocItemAnalysis = function assocItemAnalysis(state, quizId, itemAnalyses) {
  var itemAnalysisIds = (0, _immutable.List)((0, _map.default)(itemAnalyses, 'item_id'));
  return state.setIn([quizId, 'itemAnalyses'], itemAnalysisIds);
};

var assocQuizAnalysis = function assocQuizAnalysis(state, quizId, quizAnalysis) {
  return state.setIn([quizId, 'quizAnalysis'], quizAnalysis.quiz_id);
};

var addQuizzes = function addQuizzes(state, quizzes) {
  var quizHash = (0, _isArrayLike.default)(quizzes) ? (0, _keyBy.default)(quizzes, 'id') : quizzes;
  return state.mergeDeep((0, _immutable.fromJS)(quizHash));
};

var defaultState = (0, _immutable.fromJS)({});

var _default = function _default() {
  var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultState;
  var action = arguments.length > 1 ? arguments[1] : undefined;

  switch (action.type) {
    case _constants.DISASSOCIATE_QUIZ_ENTRY:
      return dissocQuizEntry(state, "".concat(action.payload.quizId), action.payload.quizEntryId);

    case _constants.ASSOCIATE_QUIZ_ENTRIES:
      return assocQuizEntry(state, "".concat(action.payload.quizId), action.payload.quizEntries);

    case _constants.ASSOCIATE_ITEM_ANALYSES:
      return assocItemAnalysis(state, "".concat(action.payload.quizId), action.payload.itemAnalyses);

    case _constants.ASSOCIATE_QUIZ_ANALYSIS:
      return assocQuizAnalysis(state, "".concat(action.payload.quizId), action.payload.quizAnalysis);

    case _constants.ADD_QUIZZES:
      return addQuizzes(state, action.payload);

    case _constants.ACTIVE_QUIZ_CHANGE:
      return state.set('activeQuizId', action.payload);

    default:
      return state;
  }
};

exports.default = _default;