#import "IdvLibrary.h"
#import <AliyunIdentityPlatform/AliyunIdentityPlatform.h>
@implementation IdvLibrary
- (NSNumber *)multiply:(double)a b:(double)b {
    NSNumber *result = @(a * b);

    return result;
}
#ifdef RCT_NEW_ARCH_ENABLED

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeIdvLibrarySpecJSI>(params);
}
#endif

+ (NSString *)moduleName
{
  return @"IdvLibrary";
}

- (void)getMetaInfo:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject {
  NSString *str = [[AliyunIdentityPlatform sharedInstance] getMetaInfo];
  resolve(str);
}

- (void)install:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject {
  [[AliyunIdentityPlatform sharedInstance] install];
  
}

- (void)installWithOptions:(nonnull NSDictionary *)options resolve:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject {
  [[AliyunIdentityPlatform sharedInstance] installWithOptions:options];

}

- (void)setCustomUIConfig:(nonnull NSString *)param resolve:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject {
  
  [[AliyunIdentityPlatform sharedInstance] setCustomUI:param complete:^(BOOL success, NSError * _Nullable error, NSDictionary *warningDict) {
    resolve(warningDict);
  }];
  
}

- (void)verify:(nonnull NSString *)certifyId extParams:(nonnull NSDictionary *)extParams resolve:(nonnull RCTPromiseResolveBlock)resolve reject:(nonnull RCTPromiseRejectBlock)reject {
  dispatch_async(dispatch_get_main_queue(), ^{
    UIViewController *vc = [self viewControllerWithWindow:nil];
    [[AliyunIdentityPlatform sharedInstance] verifyWithCertifyId:certifyId withCurrentViewController:vc withExtParams:extParams complete:^(AliyunIdentityVerifyRes *response) {
      NSMutableDictionary *dict = [NSMutableDictionary dictionary];
      [dict setValue:@(response.code) forKey:@"code"];
      [dict setValue:response.message forKey:@"message"];
      [dict setValue:response.subCode forKey:@"subCode"];
      resolve(dict);
    }];
  });
}

- (UIViewController *) viewControllerWithWindow:(UIWindow *)window {
    UIWindow *windowToUse = window;
    if(windowToUse == nil) {
        for (UIWindow *windowF in [UIApplication sharedApplication].windows) {
            if (windowF.isKeyWindow) {
                windowToUse = windowF;
                break;
            }
        }
    }
    UIViewController *topViewController = windowToUse.rootViewController;
    while (topViewController.presentingViewController) {
        topViewController = topViewController.presentingViewController;
    }
    return  topViewController;
}

@end
