import { fromJS, toJS, List, Iterable } from 'immutable';


export function createReducer(initialState) {
	return new Reducer(initialState);
}


function Reducer (state) {
	this.handlers = {}
	this.initialState = fromJS(state || {});
}

Reducer.prototype.export = function (initialState) {
	let initial = initialState || this.initialState;
	if (!Iterable.isIterable(initial)) {
		initial = fromJS(initial);
	}
	return (state = initial, action = {}) => {
		if (!this.handlers[ action.type ]) {
			return state;
		}
		return this.handlers[ action.type ](state, action);
	}
}


Reducer.prototype.handleAction = function (type, fn) {
	this.handlers[ type ] = fn;
}


Reducer.prototype.handleActions = function (actionTypes, fn) {
	actionTypes.forEach((type) => { 
		this.handlers[ type ] = fn 
	});
}

export default createReducer;

export const safe = (val) => {
    return val ? val.toJS() : {};
}