'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _immutable = require('immutable');

var _isArrayLike = require('lodash/isArrayLike');

var _isArrayLike2 = _interopRequireDefault(_isArrayLike);

var _keyBy = require('lodash/keyBy');

var _keyBy2 = _interopRequireDefault(_keyBy);

var _map = require('lodash/map');

var _map2 = _interopRequireDefault(_map);

var _constants = require('../../constants');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var assocQuizEntry = function assocQuizEntry(state, quizId, quizEntries) {
  var quizEntryIds = (0, _immutable.List)((0, _map2.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, _map2.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, _isArrayLike2.default)(quizzes) ? (0, _keyBy2.default)(quizzes, 'id') : quizzes;

  return state.mergeDeep((0, _immutable.fromJS)(quizHash));
};

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

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

  switch (action.type) {
    case _constants.DISASSOCIATE_QUIZ_ENTRY:
      return dissocQuizEntry(state, '' + action.payload.quizId, action.payload.quizEntryId);
    case _constants.ASSOCIATE_QUIZ_ENTRIES:
      return assocQuizEntry(state, '' + action.payload.quizId, action.payload.quizEntries);
    case _constants.ASSOCIATE_ITEM_ANALYSES:
      return assocItemAnalysis(state, '' + action.payload.quizId, action.payload.itemAnalyses);
    case _constants.ASSOCIATE_QUIZ_ANALYSIS:
      return assocQuizAnalysis(state, '' + 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;
  }
};