import * as React from 'react'
import * as ReactDOM from 'react-dom'
import { combineReducers } from 'redux'
import { Provider, connect } from 'react-redux'
import { Route, Switch } from 'react-router'
import { routerReducer, ConnectedRouter } from 'react-router-redux'
import { createEpicMiddleware, combineEpics, Epic } from 'redux-observable'
import { createLogger } from 'redux-logger'
import { composeWithDevTools } from 'redux-devtools-extension'
import 'rxjs'

// lml dependencies
import { history, createCosmoReduxStore, CosmoReduxStoreConfig } from '@lml/cosmo-redux-store'
import { API_REDUCER_KEY, cosmoApiReducers, cosmoApiEpics, RootState } from '@lml/cosmo-redux-api';

// pusher stuff
import { config } from './config'
import { pusherConnect } from './actions'
import { cosmoPusherEpics } from './epics'
import { PUSHER_REDUCER_KEY, pusherReducers } from './reducers'

const rootReducer = combineReducers({
    [API_REDUCER_KEY]: cosmoApiReducers,
    router: routerReducer,
    [PUSHER_REDUCER_KEY]: pusherReducers,
})

export const epicDependencies = {}

export const rootEpic = combineEpics(
    // external
    cosmoApiEpics,
    cosmoPusherEpics,
)

interface StartPusherProps {
    pusherConnect: (key: string, cluster: string, options?: any) => any
}

class StartButton extends React.Component<StartPusherProps> {

    render() {
        return (
            <button onClick={this.startPusher}>start pusher</button>
        )
    }

    private startPusher = () =>
        this.props.pusherConnect(
            config.PUSHER_KEY,
            config.PUSHER_CLUSTER
        )
}

const mapStateToProps = () => ({})
const mapDispatchToProps = { pusherConnect }
const ConnectedStartButton = connect(mapStateToProps, mapDispatchToProps)(StartButton)

/**
 * Boot up procedure
 */
const initialize = async () => {
    const localStoragePaths = ['auth']

    const storeConfig: CosmoReduxStoreConfig = {
        storage: window.localStorage,
        rootReducer,
        rootEpic,
        epicDependencies,
        localStoragePaths,
        localStorageKey: config.APP_VERSION || 'cosmo',
        disableReduxLogger: config.DISABLE_REDUX_LOGGER === 'true',
    }

    const store = createCosmoReduxStore(storeConfig)


    /**
     * Root component
     */
    const App = () => (
        <Provider store={store}>
            <ConnectedRouter history={history} >
                <div style={{ margin: '25px' }}>
                    <h2>Cosmo pusher demo</h2>
                    <p>Click start and check the console to see the pusher system in action</p>
                    <p>You may wish to login to pusher.com and use their
                        interface to fire some demo events</p>
                    <ConnectedStartButton />
                </div>
            </ConnectedRouter>
        </Provider>
    )

    /**
     * Render app
     */
    ReactDOM.render(<App />, document.getElementById('mount'))
}

initialize()
