#import "AppticsReactModule.h"
#import "AppticsPushModule.h"
#import <Apptics/Apptics.h>
#import <Apptics/Analytics.h>
#import <React/RCTLog.h>
#import <AppticsEventTracker/AppticsEventTracker.h>
#import <AppticsScreenTracker/AppticsScreenTracker.h>
#import <AppticsRateUs/APRateUs.h>
//#import <AppticsInAppUpdate/AppticsInAppUpdate.h>

#ifdef RCT_NEW_ARCH_ENABLED
#import <AppticsReactNativeSpec/AppticsReactNativeSpec.h>
#endif
#import <React/RCTAssert.h>
#import "APCrashReportUploadOperation.h"
#import <AppticsRemoteConfig/AppticsRemoteConfig.h>

@implementation UIResponder (Trackable)
+ (void)load{    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [AppticsConfig defaultConfig].enableRateUs = true;
        [Apptics initializeWithVerbose:true];
        [APLog setShouldLog:YES];
        [APLog setLogLevel:APLogLevelAll];
        [APRemoteConfig enable:true];
        [Apptics setCompleteOff:true];
    });
}
@end

#define maxDataSize 1.8
#define rt_safeDictionary(A)  ({ NSDictionary *__a = A; (__a != nil) ? __a : @{}; })

@implementation AppticsReactModule
RCT_EXPORT_MODULE()

NSUInteger childviewcontrollers;
UIWindow *window;
NSDictionary *customproperties;

+(AppticsReactModule*) shared{
    
    static dispatch_once_t onceToken;
    __strong static id _sharedObject = nil;
    dispatch_once(&onceToken, ^{
        _sharedObject = [[AppticsReactModule alloc] init];
        
        [Apptics setUserConsentPresentCompletionHandler:^(bool status, NSError *error) {
            
        }];
        
        [Apptics setUserConsentDismissCompletionHandler:^(int status) {
            [_sharedObject openSettings];
        }];

        [[NSNotificationCenter defaultCenter] addObserver:_sharedObject selector:@selector(uploadCrashSuccessNotification:) name:@"APRCTCrashUploadSuccessNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:_sharedObject selector:@selector(uploadNonFatalsSuccessNotification:) name:@"APRCTNonFatalsUploadSuccessNotification" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:_sharedObject selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:_sharedObject selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
        NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    });
    return _sharedObject;
}

- (void) applicationWillEnterForeground:(NSNotification*) notification
{
//    [AppticsReactModule shared].uniqErrors=[NSMutableDictionary new];
}

- (void) applicationDidEnterBackground:(NSNotification*) notification
{
    [self saveUniqueNonFatalDetails];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (childviewcontrollers > 1){
        double delayInSeconds = 0.5;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [window setHidden:true];
        });
    }
    childviewcontrollers = navigationController.childViewControllers.count;
}

//- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//
//}

// Example method
// See // https://reactnative.dev/docs/native-modules-ios
//RCT_REMAP_METHOD
//RCT_EXPORT_METHOD
//RCT_REMAP_METHOD(smultiply,
//                 multiplyWithA:(double)a withB:(double)b
//                 withResolver:(RCTPromiseResolveBlock)resolve
//                 withRejecter:(RCTPromiseRejectBlock)reject)
//{
//  NSNumber *result = @(a * b);
//    NSLog(@"initwithverbose is triggered! %@, %@", @(a), @(b));
//    NSLog(@"result %@",result);
//  resolve(result);
//}
// Don't compile this code when we build for the old architecture.
#ifdef RCT_NEW_ARCH_ENABLED
- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
{
    return std::make_shared<facebook::react::NativeAppticsReactModuleSpecJSI>(params);
}
#endif

/**
 This method initialises Apptics
 */

RCT_EXPORT_METHOD(init: (BOOL)status){
    [ZAPIIManager getInstance].regDeviceInprogress=false;
    [Apptics enableAutomaticScreenTracking:status];
    [Apptics setCompleteOff:false];
}

RCT_EXPORT_METHOD(initWithScreenTrackingStatus:(BOOL)enableAutoScreenTracking){
    [ZAPIIManager getInstance].regDeviceInprogress=false;
    [Apptics enableAutomaticScreenTracking:enableAutoScreenTracking];
    [Apptics setCompleteOff:false];
}


/**
 Enable automatic event tracking, it allows you to track key events in your application's lifecycle. This information can be used to improve your application's performance and stability.

 @param status boolean
 */

RCT_EXPORT_METHOD(enableAutomaticEventTracking:(BOOL) status){
    [Apptics enableAutomaticEventTracking:status];
}

/**
 Enable or disable automatic screen tracking using this method. This feature is usually enabled by default.

 @param status boolean
 */

RCT_EXPORT_METHOD(enableAutomaticScreenTracking:(BOOL) status){
    [Apptics enableAutomaticScreenTracking:status];
}

/**
 Enable or disable automatic crash tracking using this method. This feature is usually enabled by default.

 @param status boolean
 */

RCT_EXPORT_METHOD(enableAutomaticCrashTracking:(BOOL) status){
    [Apptics enableAutomaticCrashTracking:status];
}

/**
 This method allows you to include custom information with your crash report that can help you troubleshoot the issue.

 @param object any object that is conforms to JSON Encoding
 */

RCT_EXPORT_METHOD(setCustomProperties:(nonnull NSDictionary*) object){
    customproperties = object;
    [Apptics setCrashCustomProperty:object];
}

/**
 Enable the option to review the crash report before sending it.
 */
RCT_EXPORT_METHOD(enableReviewAndSendCrashReport : (BOOL) status){
    [Apptics enableReviewAndSendCrashReport:status];
}

// /**

// Use the 'complete off' method to prevent Apptics from communicating with the server. This will pause Apptics activities while the user is consenting.

// */

// RCT_EXPORT_METHOD( setCompleteOff:(BOOL) status){
//     [Apptics setCompleteOff:status];
// }

#pragma mark - Device consent

/**
 *  Returns an enum of privacy status:
 *  TrackingAuthOff=-2
 *  Unknown=-1
 *  UnAuthorized=0
 *  Authorized=1
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getPrivacyStatus){
    return @([Apptics getPrivacyStatus]);
}

/**
 *  This method will show the user the privacy options that are built into the Apptics SDK.
 */

RCT_EXPORT_METHOD(showPrivacyReviewPopup){
    dispatch_async(dispatch_get_main_queue(), ^{
        [Apptics showPrivacyConsent];
        [AppticsReactModule shared];
    });
}

// Android-only — no-op on iOS
RCT_EXPORT_METHOD(showLastSessionCrashedPopup){}

// Android-only — no-op on iOS
RCT_EXPORT_METHOD(trackScreenAttached:(NSString *)name){}
RCT_EXPORT_METHOD(trackScreenDetached:(NSString *)name){}

/**
 *  This method clears all user info from the app, including cached data and preferences.
 *
 *  - Warning:
 *  This method should not be called in a production environment.
 */

RCT_EXPORT_METHOD(resetConsentPreference){
    //    [Apptics resetConsentPreference];
}

#pragma mark — Flush

/**
 *  Flushes all events that have been tracked so far to the server right away. You might typically want to use this when the user is going to log out, or pretty much whenever you need it.
 */

RCT_EXPORT_METHOD(flush){
    [Apptics flush];
    [self saveUniqueNonFatalDetails];
    [self checkForNonFatalAndSendToServer];
}

/**
 *  This will clear all stored data on your device without sending any information to the server.
 */

RCT_EXPORT_METHOD( reset){
    [Apptics reset];
}

#pragma mark — Non-fatals apis

///**
//Use this method to track any NSError:
//
//@param error Error.
//*/
//
//RCT_EXPORT_METHOD(AP_TrackError(const char *file, int lineNumber, const char *functionName,const char *type, NSError *error,...)){
//
//}
//
///**
//Use this method to track any NSException.
//
//@param exception A handled exception
//*/
//
//RCT_EXPORT_METHOD(AP_TrackException(const char *file, int lineNumber, const char *functionName,const char *type, NSException *exception,...)){
//
//}

#pragma mark — User apis

/**
 Log the user signup to see how many users have signed up from your app

 @param userID String
 */

RCT_EXPORT_METHOD(trackSignUp:(NSString* _Nullable)userID){
    [Apptics trackSignUp:userID];
}

/**
 Log the user login to see how many users have logged in to your app

 @param userID String
 */

RCT_EXPORT_METHOD(trackLogIn:(NSString* _Nullable)userID){
    [Apptics trackLogIn:userID];
}

/**
 Log the user out to see how many users have logged out to your app.

 @param userID String.
 */

RCT_EXPORT_METHOD(trackLogOut:(NSString* _Nullable)userID){
    [Apptics trackLogOut:userID];
}

/**
 Log the user signup along with the group id.
 @param userID String, groupID String
 */

RCT_EXPORT_METHOD(trackSignUpWithGroupID:(NSString* _Nullable)userID groupId : (NSString*_Nullable)groupID){
    [Apptics trackSignUp:userID groupId:groupID];
}

/**
 Log the user login along with the group id.
 @param userID String, groupID String
 */

RCT_EXPORT_METHOD(trackLogInWithGroupID:(NSString* _Nullable)userID groupId : (NSString*_Nullable)groupID){
    [Apptics trackLogIn:userID groupId:groupID];
}

/**
 Log the user logout along with the group id.

 @param userID String, groupID String
 */

RCT_EXPORT_METHOD(trackLogOutWithGroupID:(NSString* _Nullable)userID groupId : (NSString*_Nullable)groupID){
    [Apptics trackLogOut:userID groupId:groupID];
}

/**
 Specify a user identifier which will be used to identify the user in the future. We recommend you use a unique userID.

 - Warning:
 To protect users privacy, please do not pass any personally identifiable information to this method.

 @param userID String
 */

RCT_EXPORT_METHOD(setCurrentUser:(NSString *)userID properties:(NSDictionary *)properties){
    APUser *user = [[APUser alloc] initWithUserId:userID customerGroupId:@""];
    
    for (NSString *key in properties) {
            id value = [properties objectForKey:key];
            
            if ([value isKindOfClass:[NSString class]]) {
                [user addStringProperty:key value:(NSString *)value];
            } else if ([value isKindOfClass:[NSNumber class]]) {
                NSNumber *number = (NSNumber *)value;
                
                // Detect boolean
                if (CFGetTypeID((__bridge CFTypeRef)(number)) == CFBooleanGetTypeID()) {
                    [user addBooleanProperty:key value:[number boolValue]];
                } else {
                    // NSNumber can represent int, float, double, long…
                    const char *objCType = [number objCType];
                    
                    if (strcmp(objCType, @encode(int)) == 0 ||
                        strcmp(objCType, @encode(NSInteger)) == 0) {
                        [user addIntegerProperty:key value:[number integerValue]];
                    } else if (strcmp(objCType, @encode(long)) == 0) {
                        [user addLongProperty:key value:[number longValue]];
                    } else if (strcmp(objCType, @encode(float)) == 0) {
                        [user addFloatProperty:key value:[number floatValue]];
                    } else if (strcmp(objCType, @encode(double)) == 0) {
                        [user addDoubleProperty:key value:[number doubleValue]];
                    } else {
                        // Fallback: treat as double
                        [user addDoubleProperty:key value:[number doubleValue]];
                    }
                }
            } else {
                #if DEBUG
                    RCTLog(@"Unsupported property type for key %@: %@", key, [value class]);
                #endif
            }
        }
    
    [Apptics setUser:user];
}

/**
 Specify a user identifier along with the group id.

 @param userID String
 @param groupID String
 */

RCT_EXPORT_METHOD(setUserWithOrgId:(NSString *)userID orgId:(NSString *)groupID properties:(NSDictionary *)properties){
    APUser *user = [[APUser alloc] initWithUserId:userID customerGroupId:groupID];
    
    for (NSString *key in properties) {
            id value = [properties objectForKey:key];
            
            if ([value isKindOfClass:[NSString class]]) {
                [user addStringProperty:key value:(NSString *)value];
            } else if ([value isKindOfClass:[NSNumber class]]) {
                NSNumber *number = (NSNumber *)value;
                
                // Detect boolean
                if (CFGetTypeID((__bridge CFTypeRef)(number)) == CFBooleanGetTypeID()) {
                    [user addBooleanProperty:key value:[number boolValue]];
                } else {
                    // NSNumber can represent int, float, double, long…
                    const char *objCType = [number objCType];
                    
                    if (strcmp(objCType, @encode(int)) == 0 ||
                        strcmp(objCType, @encode(NSInteger)) == 0) {
                        [user addIntegerProperty:key value:[number integerValue]];
                    } else if (strcmp(objCType, @encode(long)) == 0) {
                        [user addLongProperty:key value:[number longValue]];
                    } else if (strcmp(objCType, @encode(float)) == 0) {
                        [user addFloatProperty:key value:[number floatValue]];
                    } else if (strcmp(objCType, @encode(double)) == 0) {
                        [user addDoubleProperty:key value:[number doubleValue]];
                    } else {
                        // Fallback: treat as double
                        [user addDoubleProperty:key value:[number doubleValue]];
                    }
                }
            } else {
                #if DEBUG
                    RCTLog(@"Unsupported property type for key %@: %@", key, [value class]);
                #endif
            }
        }
    
    [Apptics setUser:user];
}


#pragma mark — Settings apis

#if !TARGET_OS_OSX && !TARGET_OS_WATCH

/**
 This method opens the screen where the user can change their analytic privacy settings.
 */

RCT_EXPORT_METHOD(openSettings){
    dispatch_async(dispatch_get_main_queue(), ^{
        //        UIWindow *window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        UIViewController *rootViewController = [UIViewController new];
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
        navigationController.delegate = [AppticsReactModule shared];
        
        window.rootViewController = navigationController;
        [window makeKeyAndVisible];
        //        window.backgroundColor = [UIColor blueColor];
        double delayInSeconds = 0.5;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [Apptics openAnalyticSettingsController: navigationController];
        });
        
        
        //        UIViewController *analyticSettingsController = [Apptics getAnalyticSettingsController];
        //        [navigationController pushViewController:analyticSettingsController animated:true];
        
    });
}

#endif

/**
 Returns the status of data tracking for the current user.

 @return int
 UsageAndCrashTrackingWithPII = 1,
 UsageAndCrashTrackingWithoutPII = 4,
 OnlyUsageTrackingWithPII = 2,
 OnlyUsageTrackingWithoutPII = 5,
 OnlyCrashTrackingWithPII = 3,
 OnlyCrashTrackingWithoutPII = 6,
 NoTracking = -1
 */

RCT_EXPORT_METHOD(getTrackingStatus:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    NSNumber *status;
    if ([Apptics trackingStatus] == true && [Apptics crashReportStatus] == true && [Apptics personalInfoTrackingStatus] == true){
        status = @(1);
    }else if ([Apptics trackingStatus] == true && [Apptics crashReportStatus] == true && [Apptics personalInfoTrackingStatus] == false){
        status = @(4);
    }else if ([Apptics trackingStatus] == true && [Apptics personalInfoTrackingStatus] == true){
        status = @(2);
    }else if ([Apptics trackingStatus] == true && [Apptics personalInfoTrackingStatus] == false){
        status = @(5);
    }else if ([Apptics crashReportStatus] == true && [Apptics personalInfoTrackingStatus] == true){
        status = @(3);
    }else if ([Apptics crashReportStatus] == true && [Apptics personalInfoTrackingStatus] == false){
        status = @(6);
    }else{
        status = @(-1);
    }
    resolve(status);
}

/**
 Returns the status of data tracking for the current user.

 @return YES if enabled else NO.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(trackingStatus){
    return @([Apptics trackingStatus]);
}

/**
 Data tracking can be enabled or disabled for the current user using this method.

 @param status boolean
 */

RCT_EXPORT_METHOD(setTrackingStatus : (double) status){
    dispatch_async(dispatch_get_main_queue(), ^{        
        [Apptics setTrackingStatus:(BOOL)status];
    });
}

/**
 Returns the status of crash tracking for the current user.

 @return YES if enabled else NO.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(crashReportStatus){
    return @([Apptics crashReportStatus]);
}

/**
 This method can be used to enable or disable crash tracking for the current user. If crash tracking is disabled, a consent message will be displayed asking the user if they wish to share the crash report.

 @param status boolean
 */

RCT_EXPORT_METHOD(setCrashReportStatus : (BOOL) status){
    dispatch_async(dispatch_get_main_queue(), ^{
        [Apptics setCrashReportStatus:status];
    });
}

/**
 Returns the status of sending personalized data, which includes the user's ID and usage data for the current user.

 @return YES if enabled else NO.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(personalInfoTrackingStatus){
    return @([Apptics personalInfoTrackingStatus]);
}

/**
 Update status of tracking data with userID for the current user.

 @param status boolean
 */

RCT_EXPORT_METHOD( setPersonalInfoTrackingStatus : (BOOL) status){
    dispatch_async(dispatch_get_main_queue(), ^{
        [Apptics setPersonalInfoTrackingStatus:status];
    });
}

/**
 Returns the logged-in status of the user associated with the device.

 @return YES if logged in else NO.
 */

RCT_EXPORT_METHOD(isUserLoggedIn:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    resolve(@([Apptics isUserLoggedIn]));
}

/**
 Data will be sent to the Apptics servers using mobile data if this method is turned on.

 @param sendData boolean
 */

RCT_EXPORT_METHOD( setSendAnalyticsDataUsingMobileData : (BOOL) sendData){
    [Apptics setSendAnalyticsDataUsingMobileData:sendData];
}

/**
 Returns the status of sending data to a server over a mobile data connection.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(sendAnalyticsDataUsingMobileData){
    return @([Apptics sendAnalyticsDataUsingMobileData]);
}

#pragma mark — Localization apis
/**
 This method returns the localized string for a given key. The keys are defined in the AppticsLocalizable.strings file.

 @param key String.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(getLocalizableStringForKey : (NSString*_Nonnull) key){
    return [Apptics getLocalizableStringForKey:key];
}

/**
 Use this method to set the language for the Analytics SDK. If the language is not found in the resource bundle, the default language will be selected.

 @param lang (code) String.
 */

RCT_EXPORT_METHOD( setDefaultLanguage : (NSString*_Nonnull) lang){
    [Apptics setDefaultLanguage:lang];
}


/**
 Use this method to update the current location of the user.

 @param location (code or name) String.
 */

RCT_EXPORT_METHOD( setCurrentLocation : (NSString*_Nonnull) location){
    [Apptics setCurrentLocation:location];
}


#if !TARGET_OS_WATCH

/**
 Choose the privacy consent screen that better suits your app.
 */

RCT_EXPORT_METHOD( setPrivacyConsentType:(ZAPrivacyConsentType)privacyConsentType){
    [Apptics setPrivacyConsentType:privacyConsentType];
}

#endif

///**
//Choose the type of tracking you want to have for your app, depending on the type of tracking chosen, the option to track anonymously will be shown in the user consent.
//@param type BOOL
//*/
//
//RCT_EXPORT_METHOD( setTypeOfAnonymity : (int) type){
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (type == 0){
//            //AnonymousOnly
//            [Apptics setTypeOfAnonymity:APAnonymousTypeNone];
//        }else if (type == 1){
//            //psudoAnonymous
//            [Apptics setTypeOfAnonymity:APAnonymousTypePseudoAnonymous];
//        } else{
//            //withPIIOnly
//                [Apptics setTypeOfAnonymity:APAnonymousTypeNone];
//        }
//    });
//}

//#pragma mark — App Update apis
//
///**
//
// After initializing Apptics, call this method to enable auto check for updates.
// @param status BOOL
// */
//
////RCT_EXPORT_METHOD( enableAutoCheckForAppUpdate : (BOOL) status){
////    [Apptics enableAutoCheckForAppUpdate:status];
////}
//
///**
//
// Apptics will present update popup up on top of any view controller on navigation stack.
//
// */
//
//RCT_EXPORT_METHOD(showNewVersionAlert){
//    [APAppUpdateManager checkForUpdateAvailability:nil with:nil];
//}
//
///**
//
// Implement your own custom in app update popup using checkForUpdate method, parse the json value returned by this method and handle the cases on your own.
//
// */
//
//RCT_EXPORT_METHOD(checkForUpdate:(RCTPromiseResolveBlock)resolve
//                  rejecter:(RCTPromiseRejectBlock)reject) {
//    [APAppUpdateManager checkForUpdateAvailability:^(NSDictionary * _Nullable updateInfo) {
//        NSDictionary *updateData = [self convertUpdateDataToJson:updateInfo];
//        if (updateData == nil){
//            reject(@"ERROR", @"No update found", [NSError errorWithDomain:@"Apptics" code:400 userInfo:@{@"type":@"error", @"message":@"No update found"}]);
//        }else{
//            resolve(updateData);
//        }
//    } with:nil];
//
//}
//
///**
// Set back the actions for custom in app update.
// @param updateId update id that you will get in checkForupdate callback handler.
// @param stat set appropriate actions listed in the enum of UpdateStats.
// */
//
//RCT_EXPORT_METHOD(sendUpdatesEngagementStats : (NSString*) updateId engagement : (NSString *) stat){
//    [[APAppUpdateManager sharedManager] updateStatsWithAction:stat AndUpdateId:@(updateId.longLongValue)];
//}
//
//-(NSDictionary*) convertUpdateDataToJson: (NSDictionary*) jsonObject{
//    if (jsonObject){
//        NSDictionary *popupInfo = jsonObject[@"popupinfo"];
//        NSDictionary *updateDetails = jsonObject[@"updatedetails"];
//        if (popupInfo && updateDetails){
//            return @{
//                @"updateid" : za_safeNumber(jsonObject[@"updateid"]),
//                @"currentversion" : za_safeString(jsonObject[@"currentversion"]),
//                @"featureTitle" : za_safeString(popupInfo[@"title"]),
//                @"features" : za_safeString(popupInfo[@"description"]),
//                @"remindMeLaterText" : za_safeString(popupInfo[@"remindmelater"]),
//                @"updateNowText" : za_safeString(popupInfo[@"updatenow"]),
//                @"neverAgainText" : za_safeString(popupInfo[@"ignore"]),
//                @"option" : za_safeNumber(updateDetails[@"option"]),
//                @"reminderDays" : za_safeNumber(updateDetails[@"reminder"]),
//                @"forceInDays" : za_safeNumber(updateDetails[@"toforce"]),
//                @"alertType" : za_safeNumber(updateDetails[@"popuptype"]),
//                @"customStoreUrl" : za_safeString(updateDetails[@"storeurl"])
//            };
//        }
//
//    } return nil;
//}

#pragma mark — Crash

/**
 This method can be used to simulate the crash for testing the crash module.
 */

RCT_EXPORT_METHOD( crash){
    [Apptics crash];
}

#pragma mark - Reachability

/**
 Returns the reachability status of a the network connection.
 */

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(isReachable){
    return @([Apptics isReachable]);
}

RCT_EXPORT_METHOD(addEvent:(NSString *)name group:(NSString *)group properties:(NSDictionary *)properties){
    [APEvent trackEvent:name andGroupName:group withProperties:properties];
}

RCT_EXPORT_METHOD(trackViewEnter:(NSString *)screenName){
    [APScreentracker trackViewEnter:screenName];
}

RCT_EXPORT_METHOD(trackViewExit:(NSString *)screenName){
    [APScreentracker trackViewExit:screenName];
}

RCT_EXPORT_METHOD(sendJSException:(NSString *)name stacktraceOrMessage:(NSString *)stacktraceOrMessage stacktrace:(NSString*)stacktrace uniqueId:(NSString*)uniqueId){
#if DEBUG
    RCTLog(@"JSException issueName: %@ - %@, stackTrace - %@", name, stacktraceOrMessage, stacktrace);
#else
    [[Analytics getInstance] saveRCTFatals:name message:stacktraceOrMessage stackTrace:stacktrace crashProperties:[self crashProperties]];
#endif
}

RCT_EXPORT_METHOD(sendNonFatalJsException:(NSString *)name stacktraceOrMessage:(NSString *)stacktraceOrMessage stacktrace:(NSString*)stacktrace uniqueId:(NSString*)uniqueId){
#if DEBUG
    RCTLog(@"JSException %@ \nissueName: %@ - %@, stackTrace - %@", uniqueId, name, stacktraceOrMessage, stacktrace);
#else
    [[Analytics getInstance] saveRCTNonFatalsUniqueId:uniqueId issueName:name message:stacktraceOrMessage stackTrace:stacktrace crashProperties:[self crashProperties]];
#endif
}

RCT_EXPORT_METHOD(activateCrashListener){

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForCrashAndSendToServer:) name:@"APCheckForCrashAndSendToServerNotification" object:nil];

    RCTSetFatalHandler(^(NSError *error) {
#if DEBUG
        @try {
#endif
            NSString *name = [NSString stringWithFormat:@"%@: %@", RCTFatalExceptionName, error.localizedDescription];
            [ZAKeyChainWrapper setString:name forKey:@"RCTFatalExceptionName"];
            // Truncate the localized description to 175 characters to avoid wild screen overflows
            NSString *message = RCTFormatError(error.localizedDescription, error.userInfo[RCTJSStackTraceKey], 175);

            // Attach an untruncated copy of the description to the userInfo, in case it is needed
            NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
            [userInfo setObject:RCTFormatError(error.localizedDescription, error.userInfo[RCTJSStackTraceKey], -1)
                         forKey:@"RCTUntruncatedMessageKey"];

            // Expected resulting exception information:
            // name: RCTFatalException: <underlying error description>
            // reason: <underlying error description plus JS stack trace, truncated to 175 characters>
            // userInfo: <underlying error userinfo, plus untruncated description plus JS stack trace>
            @throw [[NSException alloc] initWithName:name reason:message userInfo:userInfo];
#if DEBUG
        } @catch (NSException *e) {
        }
#endif
    });

    RCTSetFatalExceptionHandler(^(NSException *exception) {
#if DEBUG
        @try {
#endif
            [ZAKeyChainWrapper setString:exception.name forKey:@"RCTFatalExceptionName"];
            @throw exception;
#if DEBUG
        } @catch (NSException *e) {
        }
#endif
    });
}

void uncaughtExceptionHandler(NSException *exception) {
    // Perform data-saving operations here
    if ([ZAGlobalQueue sessionStartTime] != nil && [AppticsReactModule shared].uniqErrors.count > 0){
        NSString *crashFileName = [NSString stringWithFormat:@"%@/RCTNonFatals-meta/%@.plist", [ZAFileManager dirPathForCrash], [ZAGlobalQueue sessionStartTime]];
        [ZAFileManager archiveRCTCrashReport:[AppticsReactModule shared].uniqErrors withFileName:crashFileName];
    }
}

-(void) saveUniqueNonFatalDetails{
    if ([ZAGlobalQueue sessionStartTime] != nil && [AppticsReactModule shared].uniqErrors.count > 0){
        NSString *crashFileName = [NSString stringWithFormat:@"%@/RCTNonFatals-meta/%@.plist", [ZAFileManager dirPathForCrash], [ZAGlobalQueue sessionStartTime]];
        [ZAFileManager archiveRCTCrashReport:[AppticsReactModule shared].uniqErrors withFileName:crashFileName];
        [AppticsReactModule shared].uniqErrors=[NSMutableDictionary new];
    }
}

-(void) uploadCrashSuccessNotification : (NSNotification*) notification{
    NSArray *files = (NSArray*) notification.object;
    if (files && files.count > 0){
        for (NSString *file in files){
            NSString *filePath = [[[ZAFileManager dirPathForCrash] stringByAppendingString:@"/RCTFatals"] stringByAppendingPathComponent:file];
            if (filePath){
                [ZAFileManager removeFileFromPath:filePath];
            }
        }
    }

    [self checkForNonFatalAndSendToServer];
}

-(void) uploadNonFatalsSuccessNotification : (NSNotification*) notification{
    NSArray *files = (NSArray*) notification.object;
    if (files && files.count > 0){
        for (NSString *file in files){
            NSString *filePath = [[[ZAFileManager dirPathForCrash] stringByAppendingString:@"/RCTNonFatals"] stringByAppendingPathComponent:file];
            if (filePath){
                NSMutableDictionary *crash = [ZAFileManager unarchiveRCTCrashReportForFileName:filePath];
                NSDictionary *exceptiondetails = crash[@"exceptiondetails"];
                NSNumber *sessionStartTime=exceptiondetails[@"sessionstarttime"];
                [ZAFileManager removeFileFromPath:filePath];

                NSString *metaFilePath = [[ZAFileManager dirPathForCrash] stringByAppendingFormat:@"/RCTNonFatals-meta/%@.plist",sessionStartTime];
                [ZAFileManager removeFileFromPath:metaFilePath];
            }
        }
    }
}

-(void) checkForCrashAndSendToServer : (NSNotification*) notification{
    NSInteger crashCount = [self crashReportCount];
    if (crashCount > 0){
        if ([Analytics getInstance].enableAutomaticCrashTracking){
            //Ask for user's permission to send crash report when tracking is completely off
            if ([[ZAPIIManager getInstance] shouldSendCrashReport]){
                [self sendPendingCrashReports];
            }else{
                if ([[ZAPIIManager getInstance] shouldAskPermissionForCrashReport]){
                    [[ZAPIIManager getInstance] askPermissionToSendCrashReport:^(CARType type) {
                        if (type == CARTypeSend){
                            [self sendPendingCrashReports];
                        }else{
                            //remove crashes
                            [self deleteAllCrashReports];
                        }
                    }];
                }else{
                    //remove crashes
                    [self deleteAllCrashReports];
                }
            }
        }else{
            //remove crashes
            [self deleteAllCrashReports];
        }
    }else{
        //Check for non-fatals and send
        [self checkForNonFatalAndSendToServer];
    }
}

- (NSUInteger) crashReportCount {
    NSArray *files = [ZAFileManager getRCTCrashes];
    return files.count;
}

- (void) sendPendingCrashReports{
    NSArray *files = [ZAFileManager getRCTCrashes];
    if (files.count > 0){

        [[ZAPIIManager getInstance] newRegisterDevice:^(NSString* deviceId) {
            NSString *dirPath;

            dirPath = [[ZAFileManager dirPathForCrash] stringByAppendingString:@"/RCTFatals"];

            NSFileManager *fm = [NSFileManager defaultManager];

            __block NSDictionary *meta;
            NSMutableArray *crashInfos = [NSMutableArray new];
            NSMutableArray *reportIds = [NSMutableArray new];
            __block NSUInteger datasize=0;

            [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *crashFile = (NSString*) obj;
                NSString *filePath = [dirPath stringByAppendingPathComponent:crashFile];
                if ([fm fileExistsAtPath:filePath]){
                    NSMutableDictionary *crash = [ZAFileManager unarchiveRCTCrashReportForFileName:filePath];
                    NSDictionary *_meta = crash[@"meta"];
                    NSMutableDictionary *exceptiondetails = ((NSDictionary*)crash[@"exceptiondetails"]).mutableCopy;
                    if (exceptiondetails){
                        
                        if (exceptiondetails[@"happendat"]){
                            id happenedat = exceptiondetails[@"happendat"];
                            [exceptiondetails removeObjectForKey:@"happendat"];
                            [exceptiondetails setObject:happenedat forKey:@"happenedat"];
                        }
                        
                        if (exceptiondetails[@"reactnativemessage"]){
                            id happenedat = exceptiondetails[@"reactnativemessage"];
                            [exceptiondetails removeObjectForKey:@"reactnativemessage"];
                            [exceptiondetails setObject:happenedat forKey:@"message"];
                        }
                        if (exceptiondetails[@"numberofoccurance"]){
                            [exceptiondetails removeObjectForKey:@"numberofoccurance"];
                        }
                        if (!exceptiondetails[@"errortype"]){
                            [exceptiondetails setObject:@"reactnative" forKey:@"errortype"];
                        }
                        NSNumber *size = crash[@"size"];
                        datasize += size.integerValue;
                        if (meta && ![meta isEqualToDictionary:_meta]){
                            *stop = true;
                            return;
                        }
                        //                            IVLog(@"Size is : %.2f",(float)datasize/1024.0f/1024.0f);
                        if (((float)datasize/1024.0f/1024.0f) >= maxDataSize)
                        {
                            *stop = true;
                            return;
                        }

                        meta = _meta;
                        [crashInfos addObject:exceptiondetails];
                        [reportIds addObject:crashFile];
                        RCTLog(@"exceptiondetails :: %@",exceptiondetails);
                    }
                }
            }];
            if (meta == nil){
                meta = [ZASystemProperties appMeta];
            }

            NSString *userId = @"";
            NSString *anonid = @"";

            if ([[ZAPIIManager getInstance] isAnonymousUser]){
                //unknown or unauthorised or guest user.
                userId = @"";
                if ([Analytics getInstance].enableAnonymousTracking == true && [ZAPIIManager getInstance].anonid)
                    anonid = [ZAPIIManager getInstance].anonid;
            }else if ([[ZAPIIManager getInstance] isUserLoggedIn] && [[Analytics getInstance] getCurrentUserId]){
                userId = [[Analytics getInstance] getCurrentUserId];
            }

            if (meta && crashInfos.count > 0){
                APCrashReportUploadOperation *uploadOperation = [[APCrashReportUploadOperation alloc] initWithCrashReport:@{@"meta":meta,@"exceptiondetails":crashInfos,@"reportIDs":reportIds,@"userid":userId, @"anonid":anonid, @"isfatal":@true}];
                uploadOperation.url = self.crashUrl;
                [[ZAGlobalQueue sharedQueue].operationQueue addOperation:uploadOperation];
            }
        }];
    }
}

- (NSUInteger) nonFatalsReportCount {
    NSArray *files = [ZAFileManager getRCTNonFatals];
    return files.count;
}

- (void) sendPendingNonFatalsReports{
    NSArray *files = [ZAFileManager getRCTNonFatals];
    if (files.count > 0){

        [[ZAPIIManager getInstance] newRegisterDevice:^(NSString* deviceId) {
            NSString *dirPath;

            dirPath = [[ZAFileManager dirPathForCrash] stringByAppendingString:@"/RCTNonFatals"];

            NSFileManager *fm = [NSFileManager defaultManager];

            __block NSDictionary *meta;
            NSMutableArray *crashInfos = [NSMutableArray new];
            NSMutableArray *reportIds = [NSMutableArray new];
            __block NSUInteger datasize=0;

            [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *crashFile = (NSString*) obj;
                NSString *filePath = [dirPath stringByAppendingPathComponent:crashFile];
                if ([fm fileExistsAtPath:filePath]){
                    NSMutableDictionary *crash = [ZAFileManager unarchiveRCTCrashReportForFileName:filePath];
                    NSDictionary *_meta = crash[@"meta"];
                    NSMutableDictionary *exceptiondetails = ((NSDictionary*)crash[@"exceptiondetails"]).mutableCopy;
                    if (exceptiondetails){
                        
                        if (exceptiondetails[@"happendat"]){
                            id happenedat = exceptiondetails[@"happendat"];
                            [exceptiondetails removeObjectForKey:@"happendat"];
                            [exceptiondetails setObject:happenedat forKey:@"happenedat"];
                        }
                        
                        if (exceptiondetails[@"reactnativemessage"]){
                            id happenedat = exceptiondetails[@"reactnativemessage"];
                            [exceptiondetails removeObjectForKey:@"reactnativemessage"];
                            [exceptiondetails setObject:happenedat forKey:@"message"];
                        }
                        if (exceptiondetails[@"numberofoccurance"]){
                            [exceptiondetails removeObjectForKey:@"numberofoccurance"];
                        }
                        if (!exceptiondetails[@"errortype"]){
                            [exceptiondetails setObject:@"reactnative" forKey:@"errortype"];
                        }
                        NSNumber *size = crash[@"size"];
                        datasize += size.integerValue;
                        if (meta && ![meta isEqualToDictionary:_meta]){
                            *stop = true;
                            return;
                        }
                        //                            IVLog(@"Size is : %.2f",(float)datasize/1024.0f/1024.0f);
                        if (((float)datasize/1024.0f/1024.0f) >= maxDataSize)
                        {
                            *stop = true;
                            return;
                        }

                        meta = _meta;
                        NSString *uniqueid = crash[@"uniqueid"];
                        if (uniqueid != nil && ![uniqueid isEqual:@""]){
                            NSNumber *sessionStartTime=exceptiondetails[@"sessionstarttime"];
                            NSString *filePath = [[ZAFileManager dirPathForCrash] stringByAppendingFormat:@"/RCTNonFatals-meta/%@.plist",sessionStartTime];
                            NSDictionary *listofhappenedat = [ZAFileManager unarchiveRCTCrashReportForFileName:filePath];
                            NSArray *happened_at=listofhappenedat[uniqueid];
                            if (happened_at != nil && happened_at.count > 0){
                                [exceptiondetails setObject:[happened_at componentsJoinedByString:@","] forKey:@"listofhappenedtime"];
                                [exceptiondetails setObject:@(happened_at.count) forKey:@"happenedcount"];
                            }
                        }
                        [crashInfos addObject:exceptiondetails];
                        [reportIds addObject:crashFile];
                        RCTLog(@"exceptiondetails :: %@",exceptiondetails);
                    }
                }
            }];
            if (meta == nil || [meta[@"appreleaseversionid"] isEqual:@0]){
                meta = [ZASystemProperties appMeta];
            }

            NSString *userId = @"";
            NSString *anonid = @"";

            if ([[ZAPIIManager getInstance] isAnonymousUser]){
                //unknown or unauthorised or guest user.
                userId = @"";
                if ([Analytics getInstance].enableAnonymousTracking == true && [ZAPIIManager getInstance].anonid)
                    anonid = [ZAPIIManager getInstance].anonid;
            }else if ([[ZAPIIManager getInstance] isUserLoggedIn] && [[Analytics getInstance] getCurrentUserId]){
                userId = [[Analytics getInstance] getCurrentUserId];
            }

            if (meta && crashInfos.count > 0){
                APCrashReportUploadOperation *uploadOperation = [[APCrashReportUploadOperation alloc] initWithCrashReport:@{@"meta":meta,@"exceptiondetails":crashInfos,@"reportIDs":reportIds,@"userid":userId, @"anonid":anonid, @"isfatal":@false}];
                uploadOperation.url = self.crashUrl;
                [[ZAGlobalQueue sharedQueue].operationQueue addOperation:uploadOperation];
            }
        }];
    }
}

-(NSURL*) crashUrl {

    NSString *portalId = [ZASystemProperties sharedInstance].portalid;
    NSString *projectId = [ZASystemProperties sharedInstance].projectid;
    NSString *urlString = [NSString stringWithFormat:@"%@/hsdk/v1/%@/%@/exception",[[ZANetworking sharedManager] getBaseUrlForUserID:[ZAPIIManager getInstance].mam], portalId, projectId];

    return [NSURL URLWithString:urlString];
}

- (void) deleteAllCrashReports{
    [ZAFileManager deleteAllRCTCrashes];
    [self checkForNonFatalAndSendToServer];
}

- (void) checkForNonFatalAndSendToServer{
    NSInteger crashCount = [self nonFatalsReportCount];
    if (crashCount > 0){
        if ([[ZAPIIManager getInstance] shouldSendCrashReport]){
            [self sendPendingNonFatalsReports];
        }else{
            [ZAFileManager deleteAllRCTNonFatals];
            [ZAFileManager deleteAllRCTNonFatalsMeta];
        }
    }
}

- (NSMutableDictionary*) crashProperties
{
  ZASystemProperties *properties = [ZASystemProperties sharedInstance];
    NSDictionary *_crashProperties = @{
        @"networkstatus": za_safeNumber(properties.networkReachableStatus),
        @"serviceprovider": @0,
        @"orientation": za_safeNumber(properties.phoneOrientation),
        @"batterystatus": za_safeNumber(properties.batterylevel),
        @"edge": za_safeString(properties.currentRadioAccess),
        @"ram": za_safeString(properties.ram),
        @"rom": za_safeString(properties.rom),
        @"sessionstarttime": za_safeNumber([ZAGlobalQueue sessionStartTime]),
        @"screenname": za_safeString([ZAGlobalQueue currentScreenName]),
        @"happenedat" : @([ZASystemInfo getTimeinLong]),
        @"customproperties" : rt_safeDictionary(customproperties)
    };
    return _crashProperties.mutableCopy;
}

@end

@implementation Analytics (RCTExtension)

+(void) load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^
                  {
        double delayInSeconds = 3;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [AppticsReactModule shared].uniqErrors=[NSMutableDictionary new];
        });
    });
}

- (void) saveRCTFatals : (NSString *)issueName message : (NSString *)message stackTrace : (NSString*)stackTrace crashProperties : (NSMutableDictionary*) crashProperties;{
    NSString *appName;
    appName = [ZASystemInfo getAppName];
    [ZAFileManager createCrashDir:@"RCTFatals"];
    NSString *crashFileName = [NSString stringWithFormat:@"%@/RCTFatals/%@-report-%@.plist", [ZAFileManager dirPathForCrash], appName, [ZASystemInfo getTime]];
    NSMutableDictionary *crash = [NSMutableDictionary new];
    NSDictionary *meta = [ZASystemProperties appMeta];
    if (meta){
        [crash setObject:meta forKey:@"meta"];
    }
    [crashProperties setObject:message forKey:@"issuename"];
    [crashProperties setObject:stackTrace forKey:@"message"];
    [crashProperties setObject:@1 forKey:@"happenedcount"];
    [crashProperties setObject:[NSString stringWithFormat:@"%@",[crashProperties objectForKey:@"happenedat"]] forKey:@"listofhappenedtime"];
    [crashProperties setObject:@"reactnative" forKey:@"errortype"];
    [crash setObject:crashProperties forKey:@"exceptiondetails"];
    NSError *error;
    NSData *crashInfoData = [NSJSONSerialization dataWithJSONObject:crashProperties options:1 error:&error];
    [crash setObject:@(crashInfoData.length) forKey:@"size"];

    [ZAFileManager archiveRCTCrashReport:crash withFileName:crashFileName];

}

- (void) saveRCTNonFatalsUniqueId : (NSString*) uniqueId issueName : (NSString *)issueName message : (NSString *)message stackTrace : (NSString*)stackTrace crashProperties : (NSMutableDictionary*) crashProperties{
    if (![[AppticsReactModule shared].uniqErrors.allKeys containsObject:uniqueId]){
        NSString *appName;
        appName = [ZASystemInfo getAppName];
        [ZAFileManager createCrashDir:@"RCTNonFatals"];
        [ZAFileManager createCrashDir:@"RCTNonFatals-meta"];
        NSString *crashFileName = [NSString stringWithFormat:@"%@/RCTNonFatals/%@-report-%@.plist", [ZAFileManager dirPathForCrash], appName, [ZASystemInfo getTime]];
        NSMutableDictionary *crash = [NSMutableDictionary new];
        NSDictionary *meta = [ZASystemProperties appMeta];
        if (meta){
            [crash setObject:meta forKey:@"meta"];
        }
        [crashProperties setObject:[NSString stringWithFormat:@"%@ - %@", issueName, message] forKey:@"issuename"];
        [crashProperties setObject:stackTrace forKey:@"message"];
//        [crashProperties setObject:@1 forKey:@"numberofoccurance"];
        [crashProperties setObject:[NSString stringWithFormat:@"%@",[crashProperties objectForKey:@"happenedat"]] forKey:@"listofhappenedtime"];
        [crashProperties setObject:@"reactnative" forKey:@"errortype"];
        [crash setObject:crashProperties forKey:@"exceptiondetails"];
        NSError *error;
        NSData *crashInfoData = [NSJSONSerialization dataWithJSONObject:crashProperties options:1 error:&error];
        [crash setObject:@(crashInfoData.length) forKey:@"size"];
        [crash setObject:uniqueId forKey:@"uniqueid"];

        [ZAFileManager archiveRCTCrashReport:crash withFileName:crashFileName];
        [[AppticsReactModule shared].uniqErrors setObject:@[[ZASystemInfo getTime]].mutableCopy forKey:uniqueId];
    }else{
        NSMutableArray *happened_at=[[AppticsReactModule shared].uniqErrors objectForKey:uniqueId];
        if (happened_at.count <= 10){
            [happened_at addObject:[ZASystemInfo getTime]];
            [[AppticsReactModule shared].uniqErrors setObject:happened_at forKey:uniqueId];
        }
    }
}

@end

@implementation ZAFileManager (RCTExtension)

+ (void) archiveRCTCrashReport:(NSDictionary*)crashReport withFileName : (NSString*) filePath{

      NSDictionary *copyOfData = [NSDictionary dictionaryWithDictionary:[crashReport copy]];
      if (![NSKeyedArchiver archiveRootObject:copyOfData toFile:filePath])
      {

      }
}

+(id) unarchiveRCTCrashReportForFileName : (NSString*) filePath
{
  id unarchivedData = nil;
  @try {
    unarchivedData = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  }
  @catch (NSException *exception) {
    RCTLog(@"%@ unable to unarchive crash report in %@, starting fresh", self, filePath);
    unarchivedData = nil;
  }

  return unarchivedData;

}

+(NSArray*) getRCTCrashes{
    NSError *error;
  NSString *dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTFatals"];
    dirPath = [dirPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  NSArray *dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL URLWithString:dirPath]
                                                includingPropertiesForKeys:@[NSURLContentModificationDateKey]
                                                                   options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     error:&error];
    if (error == nil){
        NSMutableArray *files = [[NSMutableArray alloc] init];
        [dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
          NSString *filename = (NSString *)obj;
            [files addObject:filename.lastPathComponent];
        }];

        return files;
    }else{
        return @[];
    }

}

+ (void) deleteAllRCTCrashes{

    NSArray *files = [ZAFileManager getRCTCrashes];
    NSString *dirPath;
    dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTFatals"];
    NSFileManager *fm = [NSFileManager defaultManager];

    [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *crashFile = (NSString*) obj;
        NSString *filePath = [dirPath stringByAppendingPathComponent:crashFile];
        if ([fm fileExistsAtPath:filePath]){
            [ZAFileManager removeFileFromPath:filePath];
        }
    }];

}

+(NSArray*) getRCTNonFatals{
    NSError *error;
  NSString *dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTNonFatals"];
    dirPath = [dirPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  NSArray *dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL URLWithString:dirPath]
                                                includingPropertiesForKeys:@[NSURLContentModificationDateKey]
                                                                   options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     error:&error];
    if (error == nil){
        NSMutableArray *files = [[NSMutableArray alloc] init];
        [dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
          NSString *filename = (NSString *)obj;
            [files addObject:filename.lastPathComponent];
        }];

        return files;
    }else{
        return @[];
    }

}

+ (void) deleteAllRCTNonFatals{

    NSArray *files = [ZAFileManager getRCTNonFatals];
    NSString *dirPath;
    dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTNonFatals"];
    NSFileManager *fm = [NSFileManager defaultManager];

    [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *crashFile = (NSString*) obj;
        NSString *filePath = [dirPath stringByAppendingPathComponent:crashFile];
        if ([fm fileExistsAtPath:filePath]){
            [ZAFileManager removeFileFromPath:filePath];
        }
    }];

}

+(NSArray*) getRCTNonFatalsMeta{
    NSError *error;
  NSString *dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTNonFatals-meta"];
    dirPath = [dirPath stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
  NSArray *dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[NSURL URLWithString:dirPath]
                                                includingPropertiesForKeys:@[NSURLContentModificationDateKey]
                                                                   options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                     error:&error];
    if (error == nil){
        NSMutableArray *files = [[NSMutableArray alloc] init];
        [dirs enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
          NSString *filename = (NSString *)obj;
            [files addObject:filename.lastPathComponent];
        }];

        return files;
    }else{
        return @[];
    }

}

+ (void) deleteAllRCTNonFatalsMeta{

    NSArray *files = [ZAFileManager getRCTNonFatalsMeta];
    NSString *dirPath;
    dirPath = [[[self class] dirPathForCrash] stringByAppendingString:@"/RCTNonFatals-meta"];
    NSFileManager *fm = [NSFileManager defaultManager];

    [files enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *crashFile = (NSString*) obj;
        NSString *filePath = [dirPath stringByAppendingPathComponent:crashFile];
        if ([fm fileExistsAtPath:filePath]){
            [ZAFileManager removeFileFromPath:filePath];
        }
    }];

}

@end
