#import "RNKochavaMeasurement.h"

#import <StoreKit/StoreKit.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import <KochavaNetworking/KochavaNetworking-Swift.h>
#import <KochavaMeasurement/KochavaMeasurement-Swift.h>

@implementation RNKochavaMeasurement

RCT_EXPORT_MODULE(KochavaMeasurement)

// Set the logging parameters before any other access to the SDK.
// TODO do we even want to do this anymore?
+ (void) initialize {
    KVALog.shared.osLogEnabledBool = false;
    KVALog.shared.printLinesIndividuallyBool = true;
}

- (void)executeAdvancedInstruction:(NSString *)name value:(NSString *)value callbackId:(NSString * _Nullable)callbackId resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject
{
  if(callbackId == nil || callbackId.length == 0) {
    // No callback
    [KVAMeasurement.shared.networking executeAdvancedInstructionWithUniversalIdentifier:name parameter:value prerequisiteTaskIdentifierArray:nil closure_didComplete:nil];
    resolve(@"");
  } else if([callbackId isEqualToString:@"standard"]) {
    // Promise callback
    [KVAMeasurement.shared.networking executeAdvancedInstructionWithUniversalIdentifier:name parameter:value prerequisiteTaskIdentifierArray:nil closure_didComplete:^(NSString * _Nullable data) {
      resolve(data ?: @"");
    }];
  } else {
    // Persistent callback
    [KVAMeasurement.shared.networking executeAdvancedInstructionWithUniversalIdentifier:name parameter:value prerequisiteTaskIdentifierArray:nil closure_didComplete:^(NSString * _Nullable data) {
      [self emitOnExecuteAdvancedInstruction:@{
        @"id": callbackId,
        @"data": data ?: @""
      }];
    }];
    resolve(@"");
  }
}

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

@end
