package com.rosetta.messenger.network

import android.content.Context
import com.rosetta.messenger.network.connection.NetworkConnectivityFacade
import com.rosetta.messenger.network.connection.NetworkReconnectWatcher
import com.rosetta.messenger.network.connection.PacketSubscriptionFacade
import com.rosetta.messenger.network.connection.ProtocolInstanceManager
import kotlinx.coroutines.CoroutineScope

internal class RuntimeTransportAssembly(
    scope: CoroutineScope,
    networkWaitTimeoutMs: Long,
    serverAddress: String,
    getAppContext: () -> Context?,
    addLog: (String) -> Unit,
    onFastReconnectRequested: (String) -> Unit
) {
    private val networkReconnectWatcher =
        NetworkReconnectWatcher(
            scope = scope,
            networkWaitTimeoutMs = networkWaitTimeoutMs,
            addLog = addLog,
            onReconnectRequested = onFastReconnectRequested
        )

    val networkConnectivityFacade =
        NetworkConnectivityFacade(
            networkReconnectWatcher = networkReconnectWatcher,
            getAppContext = getAppContext
        )

    val protocolInstanceManager =
        ProtocolInstanceManager(
            serverAddress = serverAddress,
            addLog = addLog,
            isNetworkAvailable = networkConnectivityFacade::hasActiveInternet,
            onNetworkUnavailable = {
                networkConnectivityFacade.waitForNetworkAndReconnect("protocol_connect")
            }
        )

    private val packetSubscriptionRegistry =
        PacketSubscriptionRegistry(
            protocolProvider = protocolInstanceManager::getOrCreateProtocol,
            scope = scope,
            addLog = addLog
        )

    val packetSubscriptionFacade = PacketSubscriptionFacade(packetSubscriptionRegistry)

    fun destroyPacketSubscriptions() {
        packetSubscriptionRegistry.destroy()
    }
}
