import { NetworkElementServiceGetAllFlattenedApiArg, api } from '@api/api'
import { setDevices } from '@component/devices/reducer/device.reducer'
import { createAsyncThunk } from '@reduxjs/toolkit'
import { addRoutine } from '@shared/reducer/routine.reducer'
import { setUser } from '@shared/reducer/user.reducer'
import { Category, CategoryType } from '@shared/types/category.type'
import { RootState } from 'src/stores'
import { startListening } from '../../../stores/middleware/listener.middleware'

export const FETCH_DEVICE_ACTION = 'subscription/device/fetchDevices'

// continously fetch devices
startListening({
    actionCreator: setUser,
    effect: async (_, listenerApi) => {
        listenerApi.dispatch(
            addRoutine({
                thunk: fetchDevicesThunk,
                category: Category.DEVICE as CategoryType,
                payload: {},
            })
        )
    },
})

const FETCH_DEVICES_INTERVAL = 15000 // in ms
export const fetchDevicesThunk = createAsyncThunk(FETCH_DEVICE_ACTION, (_, thunkApi) => {
    const { user } = thunkApi.getState() as RootState

    if (!user.user?.roles) {
        throw new Error('Background device fetching failed! User data is missing. Reload page or logout and login again')
        // TODO
    }

    const payload: NetworkElementServiceGetAllFlattenedApiArg = {
        pid: Object.keys(user.user.roles)[0],
        timestamp: new Date().getTime().toString(),
    }

    const subscription = thunkApi.dispatch(
        api.endpoints.networkElementServiceGetAllFlattened.initiate(payload, {
            subscriptionOptions: {
                pollingInterval: FETCH_DEVICES_INTERVAL,
                skipPollingIfUnfocused: true,
            },
        })
    )

    return subscription
})

// save fetched devices
startListening({
    predicate: (action) =>
        api.endpoints.networkElementServiceGetAllFlattened.matchFulfilled(action),
    effect: async (action, listenerApi) => {
        listenerApi.dispatch(setDevices(action.payload.mne))
    },
})