'use strict';

var _typeof2 = require('babel-runtime/helpers/typeof');

var _typeof3 = _interopRequireDefault(_typeof2);

var _keys = require('babel-runtime/core-js/object/keys');

var _keys2 = _interopRequireDefault(_keys);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _isPlainObject = require('lodash/isPlainObject');

var _isPlainObject2 = _interopRequireDefault(_isPlainObject);

var _merge = require('lodash/merge');

var _merge2 = _interopRequireDefault(_merge);

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

module.exports = function (controllableProps) {
  return function (state, inboundState, reducedState, log) {
    var newState = (0, _assign2.default)({}, reducedState);
    (0, _keys2.default)(inboundState).forEach(function (key) {
      // if initialState does not have key, skip auto rehydration
      if (!state.hasOwnProperty(key)) return;

      // if initial state is an object but inbound state is null/undefined, skip
      if ((0, _typeof3.default)(state[key]) === 'object' && !inboundState[key]) {
        if (log) console.log('redux-persist/autoRehydrate: sub state for key `%s` is falsy but initial state is an object, skipping autoRehydrate.', key);
        return;
      }

      // if reducer modifies substate, skip auto rehydration
      if (state[key] !== reducedState[key]) {
        if (log) console.log('redux-persist/autoRehydrate: sub state for key `%s` modified, skipping autoRehydrate.', key);
        newState[key] = reducedState[key];
        return;
      }

      // otherwise take the inboundState
      if (isStatePlainEnough(inboundState[key]) && isStatePlainEnough(state[key])) {
        if (controllableProps.indexOf(key) > -1) {
          newState[key] = state[key];
        } else newState[key] = (0, _merge2.default)(state[key], inboundState[key]);
      } else newState[key] = inboundState[key]; // hard set

      if (log) console.log('redux-persist/autoRehydrate: key `%s`, rehydrated to ', key, newState[key]);
    });
    return newState;
  };
};

function isStatePlainEnough(a) {
  // isPlainObject + duck type not immutable
  if (!a) return false;
  if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) !== 'object') return false;
  if (typeof a.asMutable === 'function') return false;
  if (!(0, _isPlainObject2.default)(a)) return false;
  return true;
}
//# sourceMappingURL=stateReconciler.js.map