package com.tokilabs.proto_socket

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class HeartbeatTimerTest {
    @Test
    fun testCallbackFires() = runTest {
        var fired = false
        HeartbeatTimer(this, 100) {
            fired = true
        }

        testScheduler.advanceTimeBy(101)

        assertTrue(fired)
    }

    @Test
    fun testStopPreventsCallback() = runTest {
        var fired = false
        val timer = HeartbeatTimer(this, 100) {
            fired = true
        }
        timer.stop()

        testScheduler.advanceTimeBy(150)

        assertFalse(fired)
    }

    @Test
    fun testResetRestartsTimer() = runTest {
        val fired = CompletableDeferred<Unit>()
        val timer = HeartbeatTimer(this, 100) {
            fired.complete(Unit)
        }

        testScheduler.advanceTimeBy(80)
        timer.reset()
        testScheduler.advanceTimeBy(80)
        assertFalse(fired.isCompleted)
        testScheduler.advanceTimeBy(21)
        assertTrue(fired.isCompleted)
    }
}
