//
//  SDLanServer.swift
//  Tun
//
//  Created by 安礼成 on 2024/1/31.
//
import Foundation
import NIOCore
import NIOPosix
import SwiftProtobuf

actor SDLUDPHole {
    enum State {
        case idle
        case running
        case stopped
    }
    
    private var state: State = .idle
    private let udpHoleHandler: SDLUDPHoleHandler
    
    init() throws {
        self.udpHoleHandler = try SDLUDPHoleHandler()
    }
    
    func start() async throws -> SocketAddress {
        let localAddress = try self.udpHoleHandler.start()
        self.state = .running
        
        return localAddress
    }
    
    func messageStream() -> AsyncThrowingStream<SDLUDPHoleHandler.SDLHoleDatagram, Error> {
        return self.udpHoleHandler.messageStream
    }
    
    func send(type: SDLPacketType, data: Data, remoteAddress: SocketAddress) {
        guard self.state == .running else {
            return
        }
        
        self.udpHoleHandler.send(type: type, data: data, remoteAddress: remoteAddress)
    }
    
    func stop() async {
        guard self.state != .stopped else {
            return
        }
        
        self.state = .stopped
        self.udpHoleHandler.stop()
    }
    
    deinit {
        SDLLogger.log("[SDLUDPHoleActor] deinit", for: .debug)
    }
}

