//
//  TrustDevice.m
//  TrustDeviceReactNative
//
//  Created by LEE on 7/12/24.
//

#import "TrustDevice.h"
#import <React/RCTLog.h>
#import <React/RCTConvert.h>
#import <TDMobRisk/TDMobRisk.h>

@implementation TrustDevice

RCT_EXPORT_MODULE();


RCT_REMAP_METHOD(getSDKVersion,
                 getSDKVersionResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  NSString* version = manager->getSDKVersion();
  resolve(version);
}

RCT_EXPORT_METHOD(initWithOptions:(NSDictionary*)options)
{
  NSMutableDictionary* mutableOptions = [options mutableCopy];
    
  // 1. 判断 debug 是否为空（nil 或 NSNull）
  id debugValue = options[@"debug"];
  if (debugValue && debugValue != [NSNull null]) {
      mutableOptions[@"allowd"] = debugValue;  // 原逻辑保留
  } else {
      // debug 为空时，可能设置默认值或不设置
      mutableOptions[@"allowd"] = @(NO); // 示例默认 false
  }
  
  // 2. 增加 dataCenter 赋值给 country
  id dataCenter = options[@"dataCenter"];
  if (dataCenter && dataCenter != [NSNull null]) {
      mutableOptions[@"country"] = dataCenter;
  }
  
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  manager->initWithOptions([mutableOptions copy]);
}

RCT_REMAP_METHOD(getBlackBox,
                 getBlackBoxResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  NSString* blackBox = manager->getBlackBox();
  resolve(blackBox);
}

RCT_REMAP_METHOD(getBlackBoxAsync,
                 getBlackBoxAsyncResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  manager->getBlackBoxAsync(^(NSString* blackBox){
    resolve(blackBox);
  });
}

RCT_EXPORT_METHOD(sign:(NSString*)path
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  
  TDAPISignResult signResult = manager->sign(path);

  // 获取签名并使用
  NSString* signString = signResult.sign ? [NSString stringWithUTF8String:signResult.sign] : @"";
  // 获取状态码
  int code = signResult.code;

  // 获取错误信息
  NSString* errMsgString = signResult.msg ? [NSString stringWithUTF8String:signResult.msg] : @"";
    
  // 创建结果字典
  NSMutableDictionary *resultDict = [NSMutableDictionary dictionary];
  
  // 添加所有字段
  resultDict[@"code"] = @(code);
  resultDict[@"sign"] = signString;
  resultDict[@"msg"] = errMsgString;
  
  resolve(resultDict);
}

- (UIWindow *)getKeyWindow
{
    if (@available(iOS 13.0, *))
        {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
                {
                for (UIWindow *window in windowScene.windows)
                    {
                    if (window.isKeyWindow)
                        {
                        return window;
                        }
                    }
                }
        }
        }
    else
        {
        return [UIApplication sharedApplication].keyWindow;
        }
    return nil;
}

RCT_REMAP_METHOD(showCaptcha,
                 showCaptchaResolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject)
{
  TDMobRiskManager_t *manager = [TDMobRiskManager sharedManager];
  
  dispatch_async(dispatch_get_main_queue(), ^{
    UIWindow *keyWindow = [self getKeyWindow];
    manager->showCaptcha(keyWindow,^(TDShowCaptchaResultStruct resultStruct) {
      NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
      switch (resultStruct.resultType) {
        case TDShowCaptchaResultTypeSuccess:
          resultDictionary[@"function"] = @"onSuccess";
          resultDictionary[@"token"] = @(resultStruct.validateToken);
          break;
        case TDShowCaptchaResultTypeFailed:
          resultDictionary[@"function"] = @"onFailed";
          resultDictionary[@"errorCode"] = @(resultStruct.errorCode);
          resultDictionary[@"errorMsg"] = @(resultStruct.errorMsg);
          break;
        case TDShowCaptchaResultTypeReady:
          resultDictionary[@"function"] = @"onReady";
          break;
        default:
          break;
      }
      resolve(resultDictionary);
    });
  });
}



                  


@end


