package dev.meloda.fast.domain

import dev.meloda.fast.model.LongPollEvent
import dev.meloda.fast.model.LongPollParsedEvent

internal class LongPollEventDispatcher {
    private val listenersMap: MutableMap<LongPollEvent, MutableList<VkEventCallback<LongPollParsedEvent>>> =
        mutableMapOf()

    @Suppress("UNCHECKED_CAST")
    fun <T : LongPollParsedEvent> dispatch(eventType: LongPollEvent, event: T) {
        listenersMap[eventType]?.forEach { callback ->
            (callback as? VkEventCallback<T>)?.onEvent(event)
        }
    }

    fun dispatchAll(eventType: LongPollEvent, events: List<LongPollParsedEvent>) {
        events.forEach { event -> dispatch(eventType, event) }
    }

    @Suppress("UNCHECKED_CAST")
    fun <T : LongPollParsedEvent> registerListener(
        eventType: LongPollEvent,
        listener: VkEventCallback<T>
    ) {
        listenersMap[eventType] = (listenersMap[eventType] ?: mutableListOf())
            .also { it.add(listener as VkEventCallback<LongPollParsedEvent>) }
    }

    fun <T : LongPollParsedEvent> registerListeners(
        eventTypes: List<LongPollEvent>,
        listener: VkEventCallback<T>
    ) {
        eventTypes.forEach { eventType -> registerListener(eventType, listener) }
    }
}
