package com.tomhempel.rbarometer.network

import kotlinx.coroutines.delay

/** Keeps each sync phase visible briefly without the old long artificial pause. */
class SyncProgressPacer(
    private val delegate: SyncProgressCallback?,
) {
    private var lastEmitMs: Long = 0L

    suspend fun emit(phase: SyncPhase) {
        val callback = delegate ?: return
        val now = System.currentTimeMillis()
        if (lastEmitMs > 0L) {
            val wait = MIN_PHASE_MS - (now - lastEmitMs)
            if (wait > 0L) delay(wait)
        }
        callback(SyncProgress(phase))
        lastEmitMs = System.currentTimeMillis()
    }

    suspend fun emitFinished(phase: SyncPhase = SyncPhase.FINISHED) {
        emit(phase)
        delay(MIN_PHASE_MS)
    }

    companion object {
        const val MIN_PHASE_MS = 1_000L
    }
}
