//
//  XUDPServer.m
//  xcmd
//
//  Created by mac on 2025/2/17.
//

#import <Foundation/Foundation.h>



#import "XUDPServer.h"
#import "UDPHandler.h"

#define PORT 6001

@interface XUDPServer() {
@private GCDAsyncUdpSocket *serverSocket;
}

@end

@implementation XUDPServer

+(instancetype)sharedInstance
{
    static XUDPServer* _sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once (&oncePredicate, ^{
        _sharedInstance = [[XUDPServer alloc] init];
    });
    return _sharedInstance;
}

-(instancetype)init {
    if (self = [super init]) {
        return self;
    }
    return nil;
}

- (void) start {
    NSLog(@"XS- start udp server");
    // 避免重复创建
    if (serverSocket && !serverSocket.isClosed) {
        NSLog(@"UDP server already running");
        return;
    }
    
    [self stop]; // 清理旧资源

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    serverSocket=[[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:queue];
    NSError *error = nil;
    if (![serverSocket bindToPort:PORT error:&error])
    {
        NSLog(@"Error starting server (bind): %@", error);
        [self scheduleRestart];
        return;
    }
    if (![serverSocket beginReceiving:&error])
    {
        NSLog(@"Error starting server (recv): %@", error);
        [self scheduleRestart];
        return;
    }

}

- (void)stop {
    if (serverSocket) {
        [serverSocket close];
        serverSocket = nil;
    }
}
- (void)scheduleRestart {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), 
                   dispatch_get_main_queue(), ^{
        [self start];
    });
}


// 网络连接成功后  自动回调
- (void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
   NSLog(@"已连接到用户:ip:%@",[[NSString alloc]initWithData:address encoding:NSUTF8StringEncoding]);
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    @autoreleasepool {
        // 安全的字符串转换
        NSString *datastr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (!datastr) {
            NSLog(@"Failed to decode received data");
            return;
        }
        
        NSLog(@"XS- UDP Request>>>> %@", datastr);
        
        UDPHandler *handle = [UDPHandler sharedInstance];
        NSString *res = [handle handle:datastr];
        
        if (res) {
            NSData *responseData = [res dataUsingEncoding:NSUTF8StringEncoding];
            [sock sendData:responseData toAddress:address withTimeout:10.0 tag:300];
        }
    }
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotConnect:(NSError * _Nullable)error
{
    NSLog(@"didNotConnect:%@", error);
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
    NSLog(@"didSendDataWithTag:%ld", tag);
}


- (void)udpSocket:(GCDAsyncUdpSocket *)sock didNotSendDataWithTag:(long)tag dueToError:(NSError * _Nullable)error
{
    NSLog(@"didNotSendDataWithTag:%@", error);
}


- (void)udpSocketDidClose:(GCDAsyncUdpSocket *)sock withError:(NSError  * _Nullable)error
{
    NSLog(@"withError:%@", error);
    if (error) {
        [self scheduleRestart]; // 自动重连
    }
}


@end
