import { createSelector } from 'reselect';
import { push } from 'react-router-redux';
import { List, Map } from 'immutable';

import createReducer from '../createReducer';
import localSearch from 'helpers/LocalSearch';
import { getLaws } from './laws';


// ******************************************************************
// ACTIONS
export const SEARCH = 'search/SEARCH';
export const SEARCHED = 'search/SEARCHED';
export const SELECT_PAGE = 'search/SELECT_PAGE';



// ******************************************************************
// REDUCERS
export default createReducer(Map({
  page: 1,
  pageSize: 20,
  query: '',
  results: List(),
}), {
  [SEARCH]: (state, { payload = '' }) => state.set('query', payload),
  [SEARCHED]: (state, { payload }) => state.set('results', List(payload)),
  [SELECT_PAGE]: (state, { payload = 1 }) => state.set('page', payload),
});



// ******************************************************************
// ACTION CREATORS
export const selectSearchPage = (page = 1) => (dispatch, getState) => {
  const query = getQuery(getState());
  const pagePath = page > 1 ? '/' + page : '';
  dispatch({ type: SELECT_PAGE, payload: page || 1 });
  dispatch(push(`/suche/${query}${pagePath}`));
};

/* global window */
let debounce;
export const search = (query = '') => (dispatch, getState) => {
  dispatch({ type: SEARCH, payload: query });
  dispatch(selectSearchPage(1));
  window.clearTimeout(debounce);
  debounce = window.setTimeout(() => {
    const timer = Date.now();
    localSearch.search(query).then(result => {
      console.log(`search timer: ${Date.now() - timer}ms`);
      const refs = result.map(obj => obj.ref.split('::'));
      const laws = getLaws(getState());
      const results = refs.slice(0, 100).map(([groupkey, enumeration]) =>
        laws.get(groupkey).find(law => law.get('enumeration') === enumeration)
      );
      dispatch({ type: SEARCHED, payload: results });
    });
  }, 500);

  // dispatch({
  //   type: SEARCH,
  //   meta: { debounce: { time: 500 } },
  //   promise: api => api.get({ name: 'laws', search: query })
  // });
};



// ******************************************************************
// SELECTORS
export const getQuery = state => state.getIn(['search', 'query']);

export const getPage = state => state.getIn(['search', 'page']);

export const getPageSize = state => state.getIn(['search', 'pageSize']);

export const getResults = state => state.getIn(['search', 'results'], List());

export const getResultsByPage = createSelector(
  [ getResults, getPage, getPageSize ],
  (laws, page, size) => {
    return ({
      total: laws.size,
      results: laws.slice(size * (page-1), size * page)
    });
  }
);

@@ -1227,41 +1227,8 @@
 %7D;%0A%0A
-/* global window */%0Alet debounce;
 %0Aexp
@@ -1373,78 +1373,106 @@
 ;%0A  
-window.clearTimeout(debounce);%0A  debounce = window.setTimeout(
+return dispatch(%7B%0A    type: SEARCHED,%0A    meta: %7B debounce: %7B time: 500 %7D %7D,%0A    promise: 
 () =%3E %7B%0A
     
@@ -1463,24 +1463,26 @@
 se: () =%3E %7B%0A
+  
     const ti
@@ -1503,16 +1503,25 @@
 ();%0A    
+  return 
 localSea
@@ -1557,24 +1557,26 @@
  =%3E %7B%0A      
+  
 console.log(
@@ -1576,16 +1576,22 @@
 le.log(%60
+local 
 search t
@@ -1630,70 +1630,13 @@
 %0A   
- 
-  const refs = result.map(obj =%3E obj.ref.split('::'));%0A
      
- 
 cons
@@ -1675,83 +1675,107 @@
     
-const results = refs.slice(0, 100).map((%5Bgroupkey, enumeration%5D) =%3E%0A       
+  return result.slice(0, 100)%0A          .map(obj =%3E obj.ref.split('::'))%0A          .map((%5Bk, e%5D) =%3E
  law
@@ -1784,24 +1784,17 @@
 get(
-groupkey
+k
 ).find(l
 aw =
@@ -1793,17 +1793,13 @@
 nd(l
-aw
  =%3E l
-aw
 .get
@@ -1823,78 +1823,17 @@
 == e
-numeration)%0A      );%0A      dispatch(%7B type: SEARCHED, payload: results
+));%0A     
  %7D);
@@ -1842,19 +1842,12 @@
    %7D
-);
 %0A  %7D
-, 500
 );%0A%0A
@@ -1881,16 +1881,18 @@
 : SEARCH
+ED
 ,%0A  //  

Refactor search action to use promise.