'use strict';

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

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

var _keyBy2 = _interopRequireDefault(_keyBy);

var _immutable = require('immutable');

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

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

var addBanks = function addBanks(state, banks) {
  return state.mergeDeep((0, _immutable.fromJS)((0, _keyBy2.default)(banks, 'id')));
};

var setBankFilters = function setBankFilters(state, _ref) {
  var bankId = _ref.bankId,
      filters = _ref.filters;
  return state.setIn([bankId, 'filters'], filters);
};

var associateBankEntries = function associateBankEntries(state, bankId, bankEntryIds) {
  return state.updateIn([bankId, 'bankEntries'], function (entrySet) {
    var set = entrySet || (0, _immutable.Set)();
    return set.union(bankEntryIds);
  });
};

var disassociateBankEntries = function disassociateBankEntries(state, bankId, bankEntryId) {
  return state.updateIn([bankId, 'bankEntries'], function (bankEntriesList) {
    return bankEntriesList.filter(function (item) {
      return item !== bankEntryId;
    });
  });
};

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.ADD_BANKS:
      return addBanks(state, action.payload);
    case _constants.SET_BANK_FILTERS:
      return setBankFilters(state, action.payload);
    case _constants.ASSOCIATE_ENTRIES:
      return associateBankEntries(state, action.payload.bankId, action.payload.bankEntryIds);
    case _constants.DISASSOCIATE_ENTRY:
      return disassociateBankEntries(state, action.payload.bankId, action.payload.bankEntryId);
    case _constants.REMOVE_BANK:
      return state.remove(action.payload);
    case _constants.ARCHIVE_BANK:
      return state.setIn([action.payload, 'archived'], true);
    default:
      return state;
  }
};