package ch.threema.localcrypto

import ch.threema.common.awaitNonNull
import ch.threema.localcrypto.exceptions.BlockedByAdminException
import ch.threema.localcrypto.exceptions.RemoteSecretMonitorException
import ch.threema.localcrypto.models.RemoteSecret
import ch.threema.localcrypto.models.RemoteSecretParameters
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

class RemoteSecretMonitor(
    private val remoteSecretClient: RemoteSecretClient,
) {
    private val remoteSecretFlow = MutableStateFlow<RemoteSecret?>(null)

    @Throws(RemoteSecretMonitorException::class, BlockedByAdminException::class)
    suspend fun monitor(baseUrl: String, parameters: RemoteSecretParameters): Unit = coroutineScope {
        try {
            remoteSecretClient.createRemoteSecretLoop(baseUrl, parameters).use { loop ->
                launch {
                    remoteSecretFlow.value = loop.remoteSecret.await()
                }
                loop.run()
            }
        } finally {
            remoteSecretFlow.value = null
        }
    }

    suspend fun awaitRemoteSecretAndClear(): RemoteSecret {
        val remoteSecret = remoteSecretFlow.awaitNonNull()
        remoteSecretFlow.value = null
        return remoteSecret
    }
}
