package com.agineek.agineek_pad_plugin

import android.content.Context
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.util.Log

public class NsdConnection(
    val context: Context
) {
    companion object {
        @JvmStatic private val Tag = "NsdConnection"
    }

    private final val serviceType = "_http._tcp."
    private final val serviceName = "skillcourtapp"

    private lateinit var service: NsdServiceInfo
    private lateinit var registrationListener: NsdConnection.RegistrationListener
    private lateinit var nsdManager: NsdManager

    init {
        Log.d(Tag, "New NsdConnection object made.")
        nsdManager = context.getSystemService(Context.NSD_SERVICE) as NsdManager
    }

    private class RegistrationListener() : NsdManager.RegistrationListener {
        public override fun onServiceRegistered(p0: NsdServiceInfo) {
            // Reference issue since serviceName is private + final and is being used publicly
            //serviceName = NsdServiceInfo.getServiceName() // Update service name to resolve name conflicts.
            Log.d(Tag, "Service Registered: ${p0.getServiceName()}")
        }

        public override fun onRegistrationFailed(p0: NsdServiceInfo, p1: Int) {
            Log.e(Tag, "Service registration failed: $p1")
        }

        public override fun onServiceUnregistered(p0: NsdServiceInfo) {
            Log.d(Tag, "Service unregistered: ${p0.getServiceName()}")
        }

        public override fun onUnregistrationFailed(p0: NsdServiceInfo, p1: Int) {
            Log.e(Tag, "Service unregistration failed: $p1")
        }
    }

    public fun registerService(port: Int) {
        Log.d(Tag, "registerSevice(${port}) function called")
        registrationListener = RegistrationListener()

        var serviceInfo = NsdServiceInfo()
        serviceInfo.setServiceName(serviceName)
        serviceInfo.setServiceType(serviceType)
        serviceInfo.setPort(port)

        Log.d(Tag, "Registered NSD Service $serviceInfo")

        nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener)
    }

    public fun tearDown() {
        Log.d(Tag, "tearDown() function called")
        if (registrationListener != null) {
            Log.d(Tag, "Unregistering NSD RegistrationListener $registrationListener")
            Log.d("Debug", "Before unregister service my dude")
            nsdManager.unregisterService(registrationListener)
            Log.d("Debug", "After unregister service my dude")
        }
    }
}
