import Foundation
import OSLog
import Network

public class NsdConnection {
    public static var tag: String = "NsdConnection"
    public var logger = Logger()
    public let serviceType: String = "_http._tcp."
    public var serviceName: String = "skillcourtapp"
    public var listener: NWListener
    
    init () { }
    
    public func registerService (port: NWEndpoint.Port) throws {
        let tcpOptions = NWProtocolTCP.Options()
        tcpOptions.enableKeepalive = true
        tcpOptions.keepaliveIdle = 2
        
        let parameters = NWParameters(tls: nil, tcp: tcpOptions)
        parameters.includePeerToPeer = true
        
        listener = try NWListener(using: parameters, on: port)
        listener.service = NWListener.Service(name: serviceName, type: serviceType)
        
        listener.stateUpdateHandler = { newState in
            switch newState {
            case .ready:
                self.logger.debug("Service listener is running and able to recieve connection")
            case .failed(let error):
                self.listener.cancel()
                self.logger.debug("Service registration of listener failed with code: \(error.debugDescription)")
            case .setup:
                self.logger.debug("Service listener has been initialized but not started")
            default:
                self.logger.debug("Service listener default")
                break
            }
        }
    }
    
    public func tearDown() {
        listener.cancel()
    }
}
