//
//  RCTMUDPSetting.m
//  RNBixolonBgateLibs
//
//  Created by OhDonggeon on 2024/04/26.
//

#import <React/RCTLog.h>
#import "RCTMPosUDPSettingProxy.h"

@import frameworkMPosSDK;

@interface RCTMPosUDPSettingProxy()

@end

@implementation RCTMPosUDPSettingProxy
{
    bool hasListeners;
}

+ (BOOL)requiresMainQueueSetup {
    return NO;
}

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

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

- (NSArray<NSString*>*)supportedEvents {
    return @[@""];
}

RCT_EXPORT_METHOD(getNetworkInfos:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
    NSArray<MPosDeviceInfo*>* infos = [UDPSetting getNetworkInfos];
    NSString* result = [self convertJSONString:infos];
    
    resolve(result);
}

RCT_EXPORT_METHOD(setNetworkInfo:(NSString*)macAddress
                  ipAddress:(NSString*)ipAddress
                  subnetMask:(NSString*)subnetMask
                  gateway:(NSString*)gateway
                  useDhcp:(nonnull NSNumber*)useDhcp
                  portNumber:(nonnull NSNumber*)portNumber
                  inactivityTime:(nonnull NSNumber*)inactivityTime
                  useHttps:(nonnull NSNumber*)useHttps
                  baudrate:(nonnull NSNumber*)baudrate
                  systemName:(NSString*)systemName
                  firmwareVersion:(nonnull NSNumber*)firmwareVersion
                  timeout:(nonnull NSNumber*)timeout
                  resolve:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
    MPosDeviceInfo* info = [MPosDeviceInfo new];
    
    [info setMacAddress:macAddress];
    [info setAddress:ipAddress];
    [info setSubnetmask:subnetMask];
    [info setGateway:gateway];
    
    if (systemName.length == 0) {
        [info setInterfaceType:MPOS_INTERFACE_ETHERNET];
    } else {
        [info setInterfaceType:MPOS_INTERFACE_WIFI];
    }
    
    int8_t baudrateValue = [baudrate charValue];
    NSData* baudrateData = [NSData dataWithBytes:&baudrateValue length:1];
    
    [info setBaudrate:baudrateData];
    
    int8_t useHttpsValue = [useHttps charValue];
    NSData* useHttpsData = [NSData dataWithBytes:&useHttpsValue length:1];
    
    [info setHttp:useHttpsData];
    
    int16_t firmwareVersionShortValue = [firmwareVersion shortValue]; // 펌웨어의 length는 2여야 함
    NSData* firmwareVersionData = [NSData dataWithBytes:&firmwareVersionShortValue
                                                 length:2];
    
    [info setFwVersion:firmwareVersionData];
    
    MPOS_RESULT result = [UDPSetting setNetworkInfo:info
                                          ipAddress:ipAddress
                                         subnetMask:subnetMask
                                            gateway:gateway
                                            useDhcp:useDhcp
                                         portNumber:portNumber
                                     inactivityTime:inactivityTime
                                         systemName:[systemName isEqual: @""] ? nil : systemName
                                            timeout:timeout];
    
    if(result != MPOS_SUCCESS) {
        NSString* resultMsg = [NSString stringWithFormat:@"RESULT_CODE: %ld",(long)result];
        
        reject(@"FAIL", resultMsg, nil);
    } else {
        resolve([NSNumber numberWithInteger:result]);
    }
}

- (NSString*) convertJSONString:(NSArray<MPosDeviceInfo*>*) list {
    NSString* json = @"";
    
    json = [json stringByAppendingString:@"["];
    
    for (int index = 0; index < list.count; index++) {
        MPosDeviceInfo* item = list[index];
        
        json = [json stringByAppendingString:@"{"];
        
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"systemName\": \"%@\",", item.name]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"macAddress\": \"%@\",", item.macAddress]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"ipAddress\": \"%@\",", item.address]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"portNumber\": %@,", item.portNumber]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"subnetMask\": \"%@\",", item.subnetmask]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"gateway\": \"%@\",", item.gateway]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"useDhcp\": %@,", [item.dhcp isEqualToNumber:[NSNumber numberWithInt:1]] ? @"true" : @"false"]];
        json = [json stringByAppendingString:[NSString stringWithFormat:@"\"inactivityTime\": %@,", item.inactivityTime]];
        if (item.baudrate != nil) {
            NSUInteger baudrate;
            
            [item.baudrate getBytes:&baudrate length:sizeof(baudrate)];
            json = [json stringByAppendingString:[NSString stringWithFormat:@"\"baudrate\": %lu,", baudrate]];
        } else {
            json = [json stringByAppendingString:@"\"baudrate\": 1,"];
        }
        
        if (item.fwVersion != nil) {
            const uint8_t *bytes = item.fwVersion.bytes;
            NSUInteger length = item.fwVersion.length;
            NSMutableString * fwVersionString = [NSMutableString string];
            
            for (NSUInteger i = 0; i < length; i++) {
                [fwVersionString appendFormat:@"%hhx", bytes[i]];
            }
            
            json = [json stringByAppendingString:[NSString stringWithFormat:@"\"firmwareVersion\": %@,", [NSNumber numberWithInteger:[fwVersionString integerValue]]]];
        }
        if (item.http != nil) {
            u_int8_t useHttpsValue;
            
            [item.http getBytes:&useHttpsValue length:sizeof(useHttpsValue)];
            
            if (useHttpsValue != 0) { // useHttpsValue == 0 or 10
                json = [json stringByAppendingString:@"\"useHttps\": true"];
            } else {
                json = [json stringByAppendingString:@"\"useHttps\": false"];
            }
        } else {
            json = [json stringByAppendingString:@"\"useHttps\": false"];
        }
        
        json = [json stringByAppendingString:@"}"];
        
        if (index != list.count - 1) {
            json = [json stringByAppendingString:@","];
        }
    }
    
    json = [json stringByAppendingString:@"]"];
    
    RCTLogInfo(@"deviceInfoInJSON: %@", json);
    
    return json;
}

RCT_EXPORT_MODULE();

@end
