'use babel';

import { combineReducers } from 'redux'

const reducerCreator = actions => initialState => {
	return (state = initialState, { type, payload }) => {
		const action = actions[type];
		if (action !== null && action !== undefined) {
			return typeof action === 'function' ? action(state, payload) : action;
		} else {
			return state;
		}
	}
};

const returnPayload = (field) => (state, payload) => field ? payload[field] : payload;

const visible = reducerCreator({
	SHOW: true,
	HIDE: false
})(false);

const editor = reducerCreator({
	SHOW: returnPayload(),
	FOCUS: returnPayload(),
	['SET_EDITOR']: returnPayload()
})(null);

const searchEditor = reducerCreator({
	['SET_SEARCH_EDITOR']: returnPayload()
})(null);

const results = reducerCreator({
	HIDE: [],
	['SET_SEARCH_RESULTS']: returnPayload('results')
})([]);

const tokenIndex = reducerCreator({
	HIDE: 0,
	NEXT: (state, { resultsCount }) => {
		let next = state + 1;
		if (next >= resultsCount) {
			next = 0;
		}
		return next;
	},
	PREVIOUS: (state, { resultsCount }) => {
		let previous = state - 1;
		if (previous < 0) {
			previous = resultsCount - 1;
		}
		return previous;
	},
	SET_SEARCH_RESULTS: (state, payload) => state >= payload.results.length ? 0 : state
})(0);

const pattern = reducerCreator({
	HIDE: '',
	['SET_SEARCH_RESULTS']: returnPayload('pattern')
})('');

export default combineReducers({
	visible,
	editor,
	searchEditor,
	pattern,
	tokenIndex,
	results
});

@@ -590,18 +590,16 @@
 oad(),%0A%09
-%5B'
 SET_EDIT
@@ -596,26 +596,24 @@
 %0A%09SET_EDITOR
-'%5D
 : returnPayl
@@ -668,18 +668,16 @@
 ator(%7B%0A%09
-%5B'
 SET_SEAR
@@ -685,18 +685,16 @@
 H_EDITOR
-'%5D
 : return
@@ -759,18 +759,16 @@
 E: %5B%5D,%0A%09
-%5B'
 SET_SEAR
@@ -769,34 +769,32 @@
 T_SEARCH_RESULTS
-'%5D
 : returnPayload(
@@ -1280,10 +1280,8 @@
 ',%0A%09
-%5B'
 SET_
@@ -1298,10 +1298,8 @@
 ULTS
-'%5D
 : re

update reducers