#import "RNRainbowRn.h"
#import "AssetsHelper.h"
#import <Rainbow/Rainbow.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>
#import "PBX/PBX.h"
#import "WebrtcP2P.h"
#import <IEventEmmiter.h>
#import "Navigation.h"
#import "Logger.h"

@implementation RNRainbowRn
RCT_EXPORT_MODULE();


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

+(id)sharedManager {
    static RNRainbowRn *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
    }
    return self;
}

- (void) initRainbowServiceManager {
    NSLog(@"[RNRainbowRn] initRainbowServiceManager ");
    [self checkIfFirstInstallation];
    //start recording to logs file
    [Logger startRecordingLogs];
    [[ServicesManager sharedInstance].rtcService startCallKitWithIncomingSoundName:@"incoming-call.mp3" iconTemplate:@"logo"];
    
}

 - (NSArray *)loadRainbowConfigurations {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"rainbow-config" ofType:@"json"];
     NSLog(@"loadRainbowConfigurations: rainbow-config path: %@", filePath);
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (!data) return nil;

    NSError *error = nil;
    NSArray *configArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    
    if (error) {
        NSLog(@"Failed to parse config: %@", error.localizedDescription);
        return nil;
    }

    return configArray;
}
- (NSDictionary *)getConfigurationForCurrentHost {
    NSArray *configs = [self loadRainbowConfigurations];
    NSString *currentHost = [ServicesManager sharedInstance].myUser.server.serverDisplayedName;
    NSLog(@"currentHost: %@ configs  %@  ", currentHost, configs);

        // Find config matching the current host
        for (NSDictionary *config in configs) {
            NSLog(@"currentconfig: %@  ", config[@"HOST"]);

            if ([config[@"HOST"] isEqualToString:currentHost]) {
                return config; // Contains HOST, APP_ID, SEC_KEY
            }
        }
        
        NSLog(@"⚠️ No matching config found for host: %@", currentHost);
        return nil;
    }

- (void) checkIfFirstInstallation {
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"]) {
        //the user is the first time use the app
        //so we need to reset all the old the Credentials
        
        [[[ServicesManager sharedInstance] loginManager] resetAllCredentials];
        
        NSDictionary *spec = @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword};
        SecItemDelete((__bridge CFDictionaryRef)spec);
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}



+ (BOOL)requiresMainQueueSetup {
    return YES;
}

@end
