import React from 'react';
import { CookiesProvider } from 'react-cookie';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Redirect, Route, Router, Switch } from 'react-router-dom';
import * as Redux from 'redux';
import thunk from 'redux-thunk';

import { HistoryRouter } from 'app/models/HistoryRouter';
import { IPokemonAppExtraArguments, IRouterProps } from 'app/types';

import { PokemonService } from 'api/PokemonService';

import { PokemonExplorerReducers } from 'app/components/PokemonExplorer/reducers';
import { PokemonSelectListReducers } from 'app/components/PokemonSelectList/reducers';
import { PokemonAppReducers } from 'app/reducers';

import { ConnectedPokemonApp } from 'app/PokemonApp';

export const appReducers = Redux.combineReducers({
    pokemonAppState: PokemonAppReducers,
    pokemonSelectListState: PokemonSelectListReducers,
    pokemonExplorerState: PokemonExplorerReducers,
});

const extraArguments : IPokemonAppExtraArguments = {
    services: {
        pokemonService: new PokemonService()
    }
};

const store = Redux.createStore(
    appReducers,
    // enableBatching(appReducers),
    Redux.applyMiddleware(
        thunk.withExtraArgument(extraArguments)
    )
);

const historyRouter = new HistoryRouter(store.dispatch);

ReactDOM.render(
    <CookiesProvider>
        <Provider store={ store }>
            <Router history={ historyRouter.getHistory() }>
                <Switch>
                    <Route path={ historyRouter.getRoutePath('PokemonExplorer') }>
                        <ConnectedPokemonApp />
                    </Route>

                    <Redirect from="/" to="/explorer/1/0" />
                </Switch>
            </Router>
        </Provider>
    </CookiesProvider>,
    document.getElementById('pokemon-mount')
);

// const BATCH_ACTION_TYPE = '_BATCHING_REDUCER_BATCH_ACTION_';

// // TODO Allow this to also take ThunkAction<any, any, any>
// export function batchActions(actions : Array<Redux.Action>) : Redux.Action {
//     return action(BATCH_ACTION_TYPE, actions);
// }

// // This is called in the Provider on all Reducers
// export function enableBatching(reducer : Redux.Reducer<any>) {
//     return function batchingReducer(state : any, action : Redux.Action) {
//         if (action && (action.type === BATCH_ACTION_TYPE)) {
//             const payload = (action as Redux.Action).payload;
//             return payload.reduce(batchingReducer, state);
//         }

//         return reducer(state, action);
//     };
// }
