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

#import <Foundation/Foundation.h>

#import "XUDPClient.h"

#define HOST @"127.0.0.1"
#define PORT 6001


@interface XUDPClient() {
@private
    GCDAsyncUdpSocket *_udpSocket;
}

@end


@implementation XUDPClient

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

- (void) start
{
    if (!_udpSocket)
    {
        _udpSocket=nil;
    }
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _udpSocket = [[GCDAsyncUdpSocket alloc]initWithDelegate:self delegateQueue:queue];
    NSError *error = nil;
    if (![_udpSocket bindToPort:0 error:&error])
    {
        NSLog(@"Error binding: %@", error);
        return;
    }
    if (![_udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }
}
- (void) close
{
    if(_udpSocket) {
        [_udpSocket closeAfterSending];
    }
}
- (NSString *)dic2Json: (NSDictionary *)dict {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (error) {
        NSLog(@"dic2json err:%@", error);
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void) onShow: (NSDictionary *)data {
    NSDictionary *rq = @{
        @"url": @"/adtask/show",
        @"body": data
    };
    [self send:[self dic2Json: rq]];
}

- (void) onEnd: (NSDictionary *)data  {
    NSDictionary *rq = @{
        @"url": @"/adtask/end",
        @"body": data
    };
    [self send:[self dic2Json: rq]];
}

- (void) send: (NSString*) msg {
    NSData *data = [msg dataUsingEncoding:NSUTF8StringEncoding];
    [_udpSocket sendData:data toHost:HOST port:PORT withTimeout:-1 tag:300];
}
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didConnectToAddress:(NSData *)address
{
    NSError *error = nil;
    NSLog(@"Message didConnectToAddress: %@",[[NSString alloc]initWithData:address encoding:NSUTF8StringEncoding]);
    [_udpSocket beginReceiving:&error];
}

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

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

- (NSDictionary *) json2dic: (NSString *) jsstr {
    NSError *jsonError;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[jsstr dataUsingEncoding:NSUTF8StringEncoding]
                                          options:NSJSONReadingMutableContainers
                                            error:&jsonError];
    if (jsonError) {
        NSLog(@"json2dic error: %@", jsonError);
    }
    return dic;
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext
{
    NSString *revDada =[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Message didReceiveData :%@", revDada);
    if(self.hintBlock) {
        self.hintBlock(revDada);
    }
   
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didSendDataWithTag:(long)tag
{
     NSLog(@"Message 发送成功");
}

- (void) dealloc {
    [self close];
}

@end
