package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.ConnectionLifecycleState
import com.rosetta.messenger.network.Packet

class ReadyPacketDispatchCoordinator(
    private val bootstrapCoordinator: BootstrapCoordinator,
    private val getConnectionLifecycleState: () -> ConnectionLifecycleState,
    private val resolveAccountPublicKey: () -> String,
    private val sendPacketDirect: (Packet) -> Unit,
    private val isAuthenticated: () -> Boolean,
    private val hasActiveInternet: () -> Boolean,
    private val waitForNetworkAndReconnect: (String) -> Unit,
    private val reconnectNowIfNeeded: (String) -> Unit
) {
    fun clearReadyPacketQueue(reason: String) {
        bootstrapCoordinator.clearReadyPacketQueue(reason)
    }

    fun handleSendPacket(packet: Packet) {
        val lifecycle = getConnectionLifecycleState()
        if (
            bootstrapCoordinator.packetCanBypassReadyGate(packet) ||
                lifecycle == ConnectionLifecycleState.READY
        ) {
            sendPacketDirect(packet)
            return
        }

        bootstrapCoordinator.enqueueReadyPacket(
            packet = packet,
            accountPublicKey = resolveAccountPublicKey(),
            state = lifecycle
        )

        if (!isAuthenticated()) {
            if (!hasActiveInternet()) {
                waitForNetworkAndReconnect("ready_gate_send")
            } else {
                reconnectNowIfNeeded("ready_gate_send")
            }
        }
    }
}
