package eu.friedcutlet.yokan.ui.screens import kotlin.time.Duration import kotlin.time.TimeMark import kotlin.time.TimeSource /** * Foreground reading time of one reader session. It starts running; [pause] and [resume] exclude * background intervals, [takeSeconds] hands out the time counted so far, and [finishSeconds] closes * the session so later calls neither count nor resume. */ internal class ReadingSessionClock(private val timeSource: TimeSource = TimeSource.Monotonic) { private var startedAt: TimeMark? = timeSource.markNow() private var accumulated: Duration = Duration.ZERO private var closed = false /** Stops counting; returns false when the clock was already paused or closed. */ fun pause(): Boolean { val started = startedAt ?: return false accumulated += started.elapsedNow() startedAt = null return true } /** Starts counting again unless the clock is running or closed. */ fun resume() { if (!closed && startedAt == null) startedAt = timeSource.markNow() } /** Whole seconds counted since the last take; a running clock keeps running. */ fun takeSeconds(): Int { val running = pause() val seconds = accumulated.inWholeSeconds.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() accumulated = Duration.ZERO if (running) resume() return seconds } /** Takes the remaining seconds and closes the session; later calls return 0. */ fun finishSeconds(): Int { pause() closed = true return takeSeconds() } }