import React from 'react';
import { render } from 'react-dom';
import { PersistGate } from 'redux-persist/integration/react';
import { createStore, applyMiddleware } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import { KEY_PREFIX, REHYDRATE } from 'redux-persist/lib/constants'
import storage from 'redux-persist/lib/storage'; // localstorage
import { Provider } from 'react-redux';
import logger from 'redux-logger';
import thunk from 'redux-thunk';
import reducer from './reducers';
import promise from "redux-promise-middleware";
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const middleware = [thunk];

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, reducer)

const store = createStore(
    persistedReducer,
    applyMiddleware(...middleware, logger, promise(), thunk)
)

const persistor = persistStore(store)


//Extracted from redux-persist-crosstab https://github.com/rt2zz/redux-persist-crosstab/blob/v4.0.0-0/index.js
function crosstabSync(store, persistConfig, crosstabConfig = {}) {
    const blacklist = crosstabConfig.blacklist || null
    const whitelist = crosstabConfig.whitelist || null
    const keyPrefix = crosstabConfig.keyPrefix || KEY_PREFIX

    const { key } = persistConfig

    window.addEventListener('storage', handleStorageEvent, false)

    function handleStorageEvent(e) {
        if (e.key && e.key.indexOf(keyPrefix) === 0) {
            if (e.oldValue === e.newValue) {
                return
            }

            const statePartial = JSON.parse(e.newValue)

            /* eslint-disable flowtype/no-weak-types */
            const state = Object.keys(statePartial).reduce((state, reducerKey) => {
                /* eslint-enable flowtype/no-weak-types */
                if (whitelist && whitelist.indexOf(reducerKey) === -1) {
                    return state
                }
                if (blacklist && blacklist.indexOf(reducerKey) !== -1) {
                    return state
                }

                state[reducerKey] = JSON.parse(statePartial[reducerKey])

                return state
            }, {})

            store.dispatch({
                key,
                payload: state,
                type: REHYDRATE,
            })
        }
    }
}

crosstabSync(store, persistConfig)

render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>,
    document.getElementById('root')
)

registerServiceWorker();

store.subscribe(() => {
})

store.dispatch((dispatch) => {
    //dispatch({type: "APPEND_BREADCRUMB", breadcrumbs: {name : "home", link: "/test"}});
    //dispatch({type: LOGGED_IN, username: "reader", sessionId: "23432aasdfa"});
    //dispatch({type: LOGGED_IN, username: "reader", sessionId: "23432aasdfa"});
}
)
