package com.dong.demo013

import com.dong.demo013.TimerController
import kotlinx.atomicfu.AtomicBoolean
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay

class TimerControllerImpl : TimerController {
    private val _isRunning = atomic(false)
    private val _elapsedTime = atomic(0L)
    private var timerJob: Job? = null
    private val scope = CoroutineScope(Dispatchers.Default)
    
    override val isRunning: Boolean
        get() = _isRunning.value
    
    override val elapsedTime: Long
        get() = _elapsedTime.value
    
    override fun start() {
        if (!_isRunning.value) {
            _isRunning.value = true
            startTimer()
        }
    }
    
    override fun stop() {
        if (_isRunning.value) {
            _isRunning.value = false
            timerJob?.cancel()
        }
    }
    
    override fun reset() {
        stop()
        _elapsedTime.value = 0L
    }
    
    private fun startTimer() {
        timerJob = scope.launch {
            while (isRunning) {
                delay(1000) // 每秒递增1
                _elapsedTime.incrementAndGet()
            }
        }
    }
}