//
//  KochavaMeasurement (ReactNative)
//
//  Copyright (c) 2018 - 2023 Kochava, Inc. All rights reserved.
//

#pragma mark - Import

#import "RNKochavaMeasurement.h"

#pragma mark - Util

// Interface for the KochavaMeasurementUtil
@interface KochavaMeasurementUtil : NSObject

@end

// Common utility functions used by all of the wrappers.
// Any changes to the methods in here must be propagated to the other wrappers.
@implementation KochavaMeasurementUtil

// Log a message to the console.
+ (void)log:(nonnull NSString *)message {
    NSLog(@"KVA/Measurement: %@", message);
}

// Attempts to read an NSDictionary and returns nil if not one.
+ (nullable NSDictionary *)readNSDictionary:(nullable id)valueId {
    return [[NSDictionary class] performSelector:@selector(kva_from:) withObject:valueId];
}

// Attempts to read an NSArray and returns nil if not one.
+ (nullable NSArray *)readNSArray:(nullable id)valueId {
    return [[NSArray class] performSelector:@selector(kva_from:) withObject:valueId];
}

// Attempts to read an NSNumber and returns nil if not one.
+ (nullable NSNumber *)readNSNumber:(nullable id)valueId {
    return [[NSNumber class] performSelector:@selector(kva_from:) withObject:valueId];
}

// Attempts to read an NSString and returns nil if not one.
+ (nullable NSString *)readNSString:(nullable id)valueId {
    return [NSString kva_from:valueId];
}

// Attempts to read an NSObject and returns nil if not one.
+ (nullable NSObject *)readNSObject:(nullable id)valueId {
    return [valueId isKindOfClass:NSNull.self] ? nil : valueId;
}

// Converts an NSNumber to a double with fallback to a default value.
+ (double)convertNumberToDouble:(nullable NSNumber *)number defaultValue:(double)defaultValue {
    if(number != nil) {
        return [number doubleValue];
    }
    return defaultValue;
}

// Converts an NSNumber to a bool with fallback to a default value.
+ (BOOL)convertNumberToBool:(nullable NSNumber *)number defaultValue:(BOOL)defaultValue {
    if(number != nil) {
        return [number boolValue];
    }
    return defaultValue;
}

// Converts the deeplink result into an NSDictionary.
+ (nonnull NSDictionary *)convertDeeplinkToDictionary:(nonnull KVADeeplink *)deeplink {
    NSObject *object = [deeplink kva_toContext:KVAContext.host];
    return [object isKindOfClass:NSDictionary.class] ? (NSDictionary *)object : @{};
}

// Converts the install attribution result into an NSDictionary.
+ (nonnull NSDictionary *)convertInstallAttributionToDictionary:(nonnull KVAMeasurement_Attribution_Result *)installAttribution {
    if (KVAMeasurement.shared.startedBool) {
        NSObject *object = [installAttribution kva_toContext:KVAContext.host];
        return [object isKindOfClass:NSDictionary.class] ? (NSDictionary *)object : @{};
    } else {
        return @{
                @"retrieved": @(NO),
                @"raw": @{},
                @"attributed": @(NO),
                @"firstInstall": @(NO),
        };
    }
}

// Converts the config result into an NSDictionary.
+ (nonnull NSDictionary *)convertConfigToDictionary:(nonnull KVANetworking_Config *)config {
    return @{
            @"consentGdprApplies": @(config.consentGDPRAppliesBool),
    };
}

// Serialize an NSDictionary into a json serialized NSString.
+ (nullable NSString *)serializeJsonObject:(nullable NSDictionary *)dictionary {
    return [NSString kva_stringFromJSONObject:dictionary prettyPrintBool:NO];
}

// Parse a json serialized NSString into an NSArray.
+ (nullable NSArray *)parseJsonArray:(nullable NSString *)string {
    NSObject *object = [string kva_serializedJSONObjectWithPrintErrorsBool:YES];
    return ([object isKindOfClass:NSArray.class] ? (NSArray *) object : nil);
}

// Parse a json serialized NSString into an NSDictionary.
+ (nullable NSDictionary *)parseJsonObject:(nullable NSString *)string {
    NSObject *object = [string kva_serializedJSONObjectWithPrintErrorsBool:YES];
    return [object isKindOfClass:NSDictionary.class] ? (NSDictionary *) object : nil;
}

// Parse a NSString into a NSURL and logs a warning on failure.
+ (nullable NSURL *)parseNSURL:(nullable NSString *)string {
    NSURL *url = [NSURL URLWithString:string];
    if (url == nil && string.length > 0) {
        [KochavaMeasurementUtil log:@"Warn: parseNSURL invalid input, not a valid URL"];
    }
    return url;
}

// Builds and sends an event given an event info dictionary.
+ (void)buildAndSendEvent:(nullable NSDictionary *)eventInfo {
    if(eventInfo == nil) {
        return;
    }
    NSString *name = [KochavaMeasurementUtil readNSString:eventInfo[@"name"]];
    NSDictionary *data = [KochavaMeasurementUtil readNSDictionary:eventInfo[@"data"]];
    NSString *iosAppStoreReceiptBase64String = [KochavaMeasurementUtil readNSString:eventInfo[@"iosAppStoreReceiptBase64String"]];
    if (name.length > 0) {
        KVAEvent *event = [[KVAEvent alloc] initCustomWithEventName:name];
        if (data != nil) {
            event.infoDictionary = data;
        }
        if (iosAppStoreReceiptBase64String.length > 0) {
            event.appStoreReceiptBase64EncodedString = iosAppStoreReceiptBase64String;
        }
        [event send];
    } else {
        [KochavaMeasurementUtil log:@"Warn: sendEventWithEvent invalid input"];
    }
}

@end

#pragma mark - Methods

@implementation RNKochavaMeasurement

// Set the logging parameters before any other access to the SDK.
+ (void) initialize {
    KVALog.shared.osLogEnabledBool = false;
    KVALog.shared.printLinesIndividuallyBool = true;
}

- (dispatch_queue_t)methodQueue {
    return dispatch_get_main_queue();
}

RCT_EXPORT_MODULE()

// List of the events that can be sent from the native layer.
- (NSArray<NSString *> *)supportedEvents {
    return @[@"KochavaMeasurementInitCompleted"];
}

// void executeAdvancedInstruction(string name, string value)
RCT_EXPORT_METHOD(executeAdvancedInstruction:(NSString *)name value:(NSString *)value) {
    [KVAMeasurement.shared.networking executeAdvancedInstructionWithUniversalIdentifier:name parameter:value prerequisiteTaskIdentifierArray:nil];
}

// void setLogLevel(LogLevel logLevel)
RCT_EXPORT_METHOD(setLogLevel:(NSString *)logLevel) {
    KVALog.shared.level = [KVALog_Level from:logLevel];
}

// void setSleep(bool sleep)
RCT_EXPORT_METHOD(setSleep:(BOOL)sleep) {
    KVAMeasurement.shared.sleepBool = sleep;
}

// void setAppLimitAdTracking(bool appLimitAdTracking)
RCT_EXPORT_METHOD(setAppLimitAdTracking:(BOOL)appLimitAdTracking) {
    KVAMeasurement.shared.appLimitAdTracking.boolean = appLimitAdTracking;
}

// void registerCustomDeviceIdentifier(string name, string value)
RCT_EXPORT_METHOD(registerCustomDeviceIdentifier:(NSString *)name value:(NSString *)value) {
    [KVACustomIdentifier registerWithName:name identifier:value];
}

// void registerCustomStringValue(string name, string value)
RCT_EXPORT_METHOD(registerCustomStringValue:(NSString *)name value:(NSString *)value) {
    [KVACustomValue registerWithName:name value:value];
}

// void registerCustomBoolValue(string name, bool value)
RCT_EXPORT_METHOD(registerCustomBoolValue:(NSString *)name value:(NSNumber *)value) {
    [KVACustomValue registerWithName:name value:value];
}

// void registerCustomNumberValue(string name, number value)
RCT_EXPORT_METHOD(registerCustomNumberValue:(NSString *)name value:(NSNumber *)value) {
    [KVACustomValue registerWithName:name value:value];
}

// void registerIdentityLink(string name, string value)
RCT_EXPORT_METHOD(registerIdentityLink:(NSString *)name value:(NSString *)value) {
    [KVAIdentityLink registerWithName:name identifier:value];
}

// void enableAndroidInstantApps(string instantAppGuid)
RCT_EXPORT_METHOD(enableAndroidInstantApps:(NSString *)instantAppGuid) {
    [KochavaMeasurementUtil log:@"enableAndroidInstantApps API is not available on this platform."];
}

// void enableIosAppClips(string identifier)
RCT_EXPORT_METHOD(enableIosAppClips:(NSString *)identifier) {
    KVAAppGroups.shared.generalAppGroupIdentifier = identifier;
}

// void enableIosAtt()
RCT_EXPORT_METHOD(enableIosAtt) {
    KVAMeasurement.shared.appTrackingTransparency.enabledBool = true;
}

// void setIosAttAuthorizationWaitTime(double waitTime)
RCT_EXPORT_METHOD(setIosAttAuthorizationWaitTime:(double)waitTime) {
    KVAMeasurement.shared.appTrackingTransparency.authorizationStatusWaitTimeInterval = waitTime;
}

// void setIosAttAuthorizationAutoRequest(bool autoRequest)
RCT_EXPORT_METHOD(setIosAttAuthorizationAutoRequest:(BOOL)autoRequest) {
    KVAMeasurement.shared.appTrackingTransparency.autoRequestTrackingAuthorizationBool = autoRequest;
}

// void registerPrivacyProfile(string name, string[] keys)
RCT_EXPORT_METHOD(registerPrivacyProfile:(NSString *)name keysSerialized:(NSString *)keysSerialized) {
    NSArray *keys = [KochavaMeasurementUtil parseJsonArray:keysSerialized];

    [KVAPrivacyProfile registerWithName:name datapointKeyArray:keys];
}

// void setPrivacyProfileEnabled(string name, bool enabled)
RCT_EXPORT_METHOD(setPrivacyProfileEnabled:(NSString *)name enabled:(BOOL)enabled) {
    [KVAMeasurement.shared.privacy setEnabledBoolForProfileName:name enabledBool:enabled];
}

// void setInitCompletedListener(bool setListener)
RCT_EXPORT_METHOD(setInitCompletedListener:(BOOL *)setListener) {
    if(setListener) {
        KVAMeasurement.shared.config.closure_didComplete = ^(KVANetworking_Config * _Nonnull config) {
            NSDictionary *configDictionary = [KochavaMeasurementUtil convertConfigToDictionary:config];
            NSString *configString = [KochavaMeasurementUtil serializeJsonObject:configDictionary] ?: @"{}";
            [self sendEventWithName:@"KochavaMeasurementInitCompleted" body:configString];
        };
    } else {
        KVAMeasurement.shared.config.closure_didComplete = nil;
    }
}

// void setIntelligentConsentGranted(bool granted)
RCT_EXPORT_METHOD(setIntelligentConsentGranted:(BOOL *)granted) {
    KVAMeasurement.shared.privacy.intelligentConsent.grantedBoolNumber = [NSNumber numberWithBool:granted];
}

// bool getStarted()
RCT_EXPORT_METHOD(getStarted:(RCTPromiseResolveBlock)promiseResolve promiseReject:(RCTPromiseRejectBlock)promiseReject) {
    if(promiseResolve == nil) {
        return;
    }
    promiseResolve(@(KVAMeasurement.shared.startedBool));
}

// void start(string androidAppGuid, string iosAppGuid, string partnerName)
RCT_EXPORT_METHOD(start:(NSString *)androidAppGuid iosAppGuid:(NSString *)iosAppGuid partnerName:(NSString *)partnerName) {
    if (iosAppGuid.length > 0) {
        [KVAMeasurement.shared startWithAppGUIDString:iosAppGuid];
    } else if (partnerName.length > 0) {
        [KVAMeasurement.shared startWithPartnerNameString:partnerName];
    } else {
        // Allow the native to log the error of no app guid.
        [KVAMeasurement.shared startWithAppGUIDString:nil];
    }
}

// void shutdown(bool deleteData)
RCT_EXPORT_METHOD(shutdown:(BOOL)deleteData) {
    [KochavaMeasurement_Product.shared shutdownWithDeleteLocalDataBool:deleteData];
}

// string retrieveInstallId()
RCT_EXPORT_METHOD(retrieveInstallId:(RCTPromiseResolveBlock)promiseResolve promiseReject:(RCTPromiseRejectBlock)promiseReject) {
    if(promiseResolve == nil) {
        return;
    }
    if(KVAMeasurement.shared.startedBool) {
        promiseResolve(KVAMeasurement.shared.installIdentifier.string ?: @"");
    } else {
        promiseResolve(@"");
    }
}

// void retrieveInstallAttribution(Callback<InstallAttribution> callback)
RCT_EXPORT_METHOD(retrieveInstallAttribution:(RCTPromiseResolveBlock)promiseResolve promiseReject:(RCTPromiseRejectBlock)promiseReject) {
    if(promiseResolve == nil) {
        return;
    }

    [KVAMeasurement.shared.attribution retrieveResultWithClosure_didComplete:^(KVAMeasurement_Attribution_Result *attribution) {
        NSDictionary *attributionDictionary = [KochavaMeasurementUtil convertInstallAttributionToDictionary:attribution];
        NSString *attributionSerialized = [KochavaMeasurementUtil serializeJsonObject:attributionDictionary] ?: @"";
        promiseResolve(attributionSerialized);
    }];
}

// void processDeeplink(string path, Callback<Deeplink> callback)
RCT_EXPORT_METHOD(processDeeplink:(NSString *)pathString promiseResolve:(RCTPromiseResolveBlock)promiseResolve promiseReject:(RCTPromiseRejectBlock)promiseReject) {
    if(promiseResolve == nil) {
        return;
    }
    NSURL *path = [KochavaMeasurementUtil parseNSURL:pathString];

    [KVADeeplink processWithURL:path closure_didComplete:^(KVADeeplink *_Nonnull deeplink) {
        NSDictionary *deeplinkDictionary = [KochavaMeasurementUtil convertDeeplinkToDictionary:deeplink];
        NSString *deeplinkSerialized = [KochavaMeasurementUtil serializeJsonObject:deeplinkDictionary] ?: @"";
        promiseResolve(deeplinkSerialized);
    }];
}

// void processDeeplinkWithOverrideTimeout(string path, double timeout, Callback<Deeplink> callback)
RCT_EXPORT_METHOD(processDeeplinkWithOverrideTimeout:(NSString *)pathString timeout:(double)timeout promiseResolve:(RCTPromiseResolveBlock)promiseResolve promiseReject:(RCTPromiseRejectBlock)promiseReject) {
    if(promiseResolve == nil) {
        return;
    }
    NSURL *path = [KochavaMeasurementUtil parseNSURL:pathString];

    [KVADeeplink processWithURL:path timeoutTimeInterval:timeout closure_didComplete:^(KVADeeplink *_Nonnull deeplink) {
        NSDictionary *deeplinkDictionary = [KochavaMeasurementUtil convertDeeplinkToDictionary:deeplink];
        NSString *deeplinkSerialized = [KochavaMeasurementUtil serializeJsonObject:deeplinkDictionary] ?: @"";
        promiseResolve(deeplinkSerialized);
    }];
}

// void registerDefaultEventStringParameter(string name, string value)
RCT_EXPORT_METHOD(registerDefaultEventStringParameter:(nonnull NSString *)name value:(NSString *)value) {
    [KVAEvent_DefaultParameter registerWithName:name value:value];
}

// void registerDefaultEventBoolParameter(nonnull string name, bool value)
RCT_EXPORT_METHOD(registerDefaultEventBoolParameter:(nonnull NSString *)name value:(nullable NSNumber *)value) {
    [KVAEvent_DefaultParameter registerWithName:name value:value];
}

// void registerDefaultEventNumberParameter(string name, number value)
RCT_EXPORT_METHOD(registerDefaultEventNumberParameter:(nonnull NSString *)name value:(NSNumber *)value) {
    [KVAEvent_DefaultParameter registerWithName:name value:value];
}

// void registerDefaultEventUserId(string value)
RCT_EXPORT_METHOD(registerDefaultEventUserId:(NSString *)value) {
    [KVAEvent_DefaultParameter registerWithUserIdString:value];
}

// void sendEvent(string name)
RCT_EXPORT_METHOD(sendEvent:(NSString *)name) {
    if(name.length > 0) {
        [KVAEvent sendCustomWithEventName:name];
    } else {
        [KochavaMeasurementUtil log:@"Warn: sendEvent invalid input"];
    }
}

// void sendEventWithString(string name, string data)
RCT_EXPORT_METHOD(sendEventWithString:(NSString *)name data:(NSString *)data) {
    if(name.length > 0) {
        [KVAEvent sendCustomWithEventName:name infoString:data];
    } else {
        [KochavaMeasurementUtil log:@"Warn: sendEventWithString invalid input"];
    }
}

// void sendEventWithDictionary(string name, object data)
RCT_EXPORT_METHOD(sendEventWithDictionary:(NSString *)name dataSerialized:(NSString *)dataSerialized) {
    NSDictionary *data = [KochavaMeasurementUtil parseJsonObject:dataSerialized];

    if (name.length > 0) {
        [KVAEvent sendCustomWithEventName:name infoDictionary:data];
    } else {
        [KochavaMeasurementUtil log:@"Warn: sendEventWithDictionary invalid input"];
    }
}
// void sendEventWithEvent(Event event)
RCT_EXPORT_METHOD(sendEventWithEvent:(NSString *)eventSerialized) {
    NSDictionary *eventInfo = [KochavaMeasurementUtil parseJsonObject:eventSerialized];

    [KochavaMeasurementUtil buildAndSendEvent:eventInfo];
}

@end
