//
//  BonjourConnection.swift
//  HeadNavigationClient
//
//  Created by Sergii Kryvoblotskyi on 5/20/21.
//

import AppKit

class BonjourConnection: NSObject {
    
    var onGestureReceived: ((HeadGesture) -> Void)?
    
    let internalQueue = DispatchQueue(label: "BonjourConnection.internal")
    let connection: DTBonjourDataConnection
    
    init(service: NetService) {
        self.connection = DTBonjourDataConnection(service: service)
        super.init()
        self.connection.delegate = self
    }
    
    func open() {
        connection.open()
    }
    
    func close() {
        connection.close()
    }
}

extension BonjourConnection: DTBonjourDataConnectionDelegate {
    
    func connection(_ connection: DTBonjourDataConnection!, didReceive object: Any!) {
        self.internalQueue.async {
            guard let data = object as? Data else { return }
            let decoder = JSONDecoder()
            do {
                let gesture = try decoder.decode(HeadGesture.self, from: data)
                DispatchQueue.main.async {
                    self.onGestureReceived?(gesture)
                }
            } catch {
                print(error)
            }
        }
    }
}
