package ch.dissem.yaep.ui.common

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map

class GameTimer {

    private var startTime: Long = 0L
    private var stopTime: Long = 0L

    val isRunning: Boolean
        get() = startTime != 0L && stopTime == 0L

    val elapsedSeconds: Flow<Long> = flow {
        emit(0L)
        while (startTime == 0L) {
            delay(100)
        }
        var previousSeconds = 0L
        while (stopTime == 0L) {
            val elapsedSeconds = System.currentTimeMillis() / 1000 - startTime
            if (elapsedSeconds != previousSeconds) {
                emit(elapsedSeconds)
            }
            delay(100)
            previousSeconds = elapsedSeconds
        }
        emit(stopTime - startTime)
    }

    val elapsedTime: Flow<String> = elapsedSeconds.map { seconds ->
        val minutes = seconds / 60
        val hours = minutes / 60
        val remainingMinutes = minutes % 60
        val remainingSeconds = seconds % 60
        if (hours == 0L) {
            "%02d:%02d".format(minutes, remainingSeconds)
        } else {
            "%02d:%02d:%02d".format(hours, remainingMinutes, remainingSeconds)
        }
    }

    fun start() {
        if (startTime == 0L) {
            startTime = System.currentTimeMillis() / 1000
        }
    }

    fun stop() {
        if (isRunning) {
            stopTime = System.currentTimeMillis() / 1000
        }
    }

}