import * as moment from 'moment'
import { Observable } from 'rxjs'
import { combineEpics, ActionsObservable } from 'redux-observable'
import { Store } from 'redux'
import { PusherMetadataModel } from '../interfaces'
import { getMetadataState } from '../selectors'
import { RootState } from '../reducers'
import {
    PUSHER_CONNECTION_SUCCESS,
    PusherConnectAction,
    pusherHealthcheckSuccess,
    pusherHealthcheckTimeout,
} from '../actions'

// we must have a
const MIN_HEALTHCHECK_INTERVAL = 120000

export const pusherHealthcheck =
    (action$: ActionsObservable<any>, store: Store<RootState>): Observable<any> =>
        action$.ofType(PUSHER_CONNECTION_SUCCESS)
            .mergeMap((action: PusherConnectAction) =>
                Observable.interval(120000).map(i => {
                    const state = store.getState()
                    const metadata = getMetadataState(state)
                    const now = moment()
                    let timedoutChannels = Object.keys(metadata)
                        .filter((channel: string) => {
                            const item = metadata[channel]
                            const diff = now.diff(moment(item.timestamp))
                            return diff > MIN_HEALTHCHECK_INTERVAL
                        })
                    if (timedoutChannels.length) {
                        return pusherHealthcheckTimeout(timedoutChannels)
                    }
                    return pusherHealthcheckSuccess()
                })
            )