#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <zy_multicompany_bio_lib_ios/zy_multicompany_bio_lib_ios-Swift.h>

#import "ZyprotectabioModule-Bridging-Header.h"

@implementation ZyprotectabioModule

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(onZyBioCapture:(NSDictionary *)opcional
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
  dispatch_async(dispatch_get_main_queue(), ^{
    @try {

      UIViewController *ctrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

      ReactRequest *request = [ReactRequest new];
      request.token = opcional[@"accessToken"];
      request.bioTiDoc = [self safeString:opcional[@"tiDocumento"] defaultValue:@""];
      request.bioNuDoc = opcional[@"nuDocumento"];
      request.bioPais = [self safeString:opcional[@"bioPais"] defaultValue:@"PE"];
      request.idFlujo = [[self safeNumber:opcional[@"idFlujo"] defaultValue:@185] integerValue];
      request.url = [self safeString:opcional[@"urlSource"] defaultValue:@"POC"];
      request.company = @"PROTECTA";

      ZyReactComp *biomatch = [[ZyReactComp alloc] initOnView:ctrl];

      [biomatch reactValidacionFacial:request
                          completion:^(ReactResponse *response) {

        resolve(@{
          @"codError": response.codError ?: @"",
          @"deError": response.deError ?: @"",
          @"codBioError": response.codBioError ?: @"",
          @"deBioError": response.deBioError ?: @"",
          @"coErrorButton": response.coErrorButton ?: @"",
          @"deErrorButton": response.deErrorButton ?: @"",
          @"idSolicitud": response.bmoNuSolicitud ?: @""
        });

      }];

    } @catch (NSException *exception) {
      reject(@"ERROR", exception.reason, nil);
    }
  });
}

#pragma mark - Safe helpers

- (NSString *)safeString:(id)value defaultValue:(NSString *)defaultValue {
  if (value == nil || value == [NSNull null]) {
    return defaultValue;
  }
  if ([value isKindOfClass:[NSString class]]) {
    return value;
  }
  return [value description];
}

- (NSNumber *)safeNumber:(id)value defaultValue:(NSNumber *)defaultValue {

    if (value == nil || value == [NSNull null]) {
        return defaultValue;
    }

    NSNumber *number = nil;

    if ([value isKindOfClass:[NSNumber class]]) {
        number = value;
    } else if ([value isKindOfClass:[NSString class]]) {
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        number = [formatter numberFromString:value];
    }

    if (number == nil || [number integerValue] == 0) {
        return defaultValue;
    }

    return number;
}

@end
