package com.rosetta.messenger.network.connection

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class OwnProfileFallbackTimerService(
    private val scope: CoroutineScope,
    private val fallbackTimeoutMs: Long,
    private val onTimeout: (Long) -> Unit
) {
    @Volatile private var timeoutJob: Job? = null

    fun schedule(sessionGeneration: Long) {
        cancel()
        timeoutJob =
            scope.launch {
                delay(fallbackTimeoutMs)
                onTimeout(sessionGeneration)
            }
    }

    fun cancel() {
        timeoutJob?.cancel()
        timeoutJob = null
    }
}
