package wang.yaojia.webterm.testsupport

import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import wang.yaojia.webterm.wire.HostEndpoint
import wang.yaojia.webterm.wire.PingableTermTransport

class FakePingableTermTransportTest {
    private fun endpoint(): HostEndpoint =
        requireNotNull(HostEndpoint.fromBaseUrl("http://192.168.1.5:3000"))

    @Test
    fun connectPingableReturnsSharedScriptablePinger() = runTest {
        val transport = FakePingableTermTransport()
        transport.pinger.scriptPongs(true, false)

        val pingable = transport.connectPingable(endpoint())

        assertEquals(true, pingable.pinger.ping())
        assertEquals(false, pingable.pinger.ping())
        assertEquals(true, pingable.pinger.ping()) // default once the scripted queue drains
        assertEquals(3, transport.pinger.pingCallCount)
        assertEquals(1, transport.connectPingableCount)
        assertEquals(listOf(endpoint()), transport.connectAttempts) // base recording still works
    }

    @Test
    fun isRecognizedAsPingableTransport() {
        val transport: Any = FakePingableTermTransport()
        assertTrue(transport is PingableTermTransport)
    }

    @Test
    fun pingerUsesConfiguredDefaultWhenUnscripted() = runTest {
        val pinger = FakeConnectionPinger(defaultPong = false)
        assertEquals(false, pinger.ping())
        assertEquals(false, pinger.ping())
        assertEquals(2, pinger.pingCallCount)
    }
}
