package com.tokilabs.proto_socket

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

class HeartbeatTimer(
    private val scope: CoroutineScope,
    private val delayMs: Long,
    private val callback: suspend () -> Unit,
) {
    private var job: Job? = null

    init {
        reset()
    }

    fun reset(delayMs: Long = this.delayMs) {
        job?.cancel()
        job = scope.launch {
            delay(delayMs)
            callback()
        }
    }

    fun stop() {
        job?.cancel()
        job = null
    }
}
