package net.fudiyama.libqx1

import net.fudiyama.libqx1.ssdp.DeviceDescription
import org.junit.After
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.net.NetworkInterface
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

class CameraManagerTest {
    lateinit var cameraManager: CameraManager

    @Before
    fun setup() {
        cameraManager = CameraManager(CameraManager.getNetworkInterfaces()[0])
    }

    @After
    fun release() {
        cameraManager.release()
    }

    @Test
    fun testGetNetworkInterfaces() {
        val interfaces: Array<NetworkInterface> = CameraManager.getNetworkInterfaces()
        Assert.assertNotNull(interfaces)

        for (ifs in interfaces) {
            println(ifs)
        }
    }

    @Test
    fun testDiscovery() {
        var discoveredDescription: DeviceDescription? = null
        val startLatch = CountDownLatch(1)
        val finishLatch = CountDownLatch(1)
        val discoveryListener = object : DiscoveryListener {
            override fun onDiscoveryStarted() {
                println("onDiscoveryStarted")
                startLatch.countDown()
            }

            override fun onDiscovered(description: DeviceDescription) {
                println("onDiscovered description=$description")
                discoveredDescription = description
            }

            override fun onDiscoveryFinished() {
                println("onDiscoveryFinished")
                finishLatch.countDown()
            }
        }

        cameraManager.registerDiscoveryListener(discoveryListener)
        cameraManager.discovery()
        Assert.assertTrue(startLatch.await(1, TimeUnit.SECONDS))
        Assert.assertTrue(finishLatch.await(10, TimeUnit.SECONDS))
        Assert.assertNotNull(discoveredDescription)
        cameraManager.unregisterDiscoveryListener(discoveryListener)
    }
}