package com.rosetta.messenger.network.connection

import com.rosetta.messenger.network.HandshakeDevice
import com.rosetta.messenger.network.Protocol

class ConnectionOrchestrator(
    private val hasActiveInternet: () -> Boolean,
    private val waitForNetworkAndReconnect: (String) -> Unit,
    private val stopWaitingForNetwork: (String) -> Unit,
    private val getProtocol: () -> Protocol,
    private val persistHandshakeCredentials: (publicKey: String, privateHash: String) -> Unit,
    private val buildHandshakeDevice: () -> HandshakeDevice
) {
    fun handleConnect(reason: String) {
        if (!hasActiveInternet()) {
            waitForNetworkAndReconnect("connect:$reason")
            return
        }
        stopWaitingForNetwork("connect:$reason")
        getProtocol().connect()
    }

    fun handleFastReconnect(reason: String) {
        if (!hasActiveInternet()) {
            waitForNetworkAndReconnect("reconnect:$reason")
            return
        }
        stopWaitingForNetwork("reconnect:$reason")
        getProtocol().reconnectNowIfNeeded(reason)
    }

    fun handleAuthenticate(publicKey: String, privateHash: String) {
        runCatching { persistHandshakeCredentials(publicKey, privateHash) }
        val device = buildHandshakeDevice()
        getProtocol().startHandshake(publicKey, privateHash, device)
    }
}
