import * as Pusher from 'pusher-js'
import { Observable } from 'rxjs'
import { combineEpics, ActionsObservable } from 'redux-observable'
import { Store } from 'redux'
import { getCourierById, setLocationByObjectId } from '@lml/cosmo-redux-api'
import { LocationModel } from '@lml/cosmo-ts-data'
import { RootState } from '../reducers'
import { pusherSubscribeChannel, PUSHER_CONNECTION_SUCCESS } from '../actions'

// this is annoyingly slightly different from the normal location interface
// but no matter
export interface PusherLocationPing {
    objectId: string
    refId: string
    latitude: number
    longitude: number
    timestamp: string
}

export const subscribeToPings =
    (action$: ActionsObservable<any>, store: Store<RootState>): Observable<any> =>
        action$.ofType(PUSHER_CONNECTION_SUCCESS)
            .mapTo(pusherSubscribeChannel(
                'ping',
                'COURIER_PING',
                (message: PusherLocationPing) => {
                    const { objectId, refId, latitude, longitude, timestamp } = message

                    const location: LocationModel = {
                        objectId,
                        refId,
                        position: {
                            type: 'point',
                            coordinates: {
                                latitude,
                                longitude,
                            }
                        },
                        timestamp,
                    }
                    return setLocationByObjectId(location)

                    // it's possible to do this so that we only care
                    // about saving the courier's location if they are in the state already
                    // const state = store.getState()
                    // const courier = getCourierById(state, objectId)

                    // if (courier) {
                    // } else {
                    //     return { type: 'COURIER_NOT_IN_STATE ' }
                    // }


                }
            ))
