//
//  AppConfiguration.m
//  rainbow
//
//  Created by Doha Tubaileh on 9/26/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import "AppConfiguration.h"
#import <React/RCTLog.h>
#import "Rainbow/Rainbow.h"
#import "RNRainbowRn.h"
#import "IEventEmmiter.h"
#import "Contact+DictRepresentation.h"
#import "NSData+Base64String.h"
#import "AppConfigEventsNames.h"

@interface AppConfiguration ()
@property (strong, nonatomic) IEventEmmiter *eventEmitter;
@property (nonatomic, weak) RCTBridge *bridge;

@end

@implementation AppConfiguration
RCT_EXPORT_MODULE();

- (instancetype)init {
    self = [super init];
    if (self) {
        //do any init here
    }
    return self;
}

- (void)dealloc {
    
}

RCT_EXPORT_METHOD(getAppConfiguration) {
    NSLog(@"[AppConfiguration] getAppConfiguration called");
    
    
    NSString *iconName = @"AppIcon"; // Default name for the app icon set in Assets.xcassets
    UIImage *appIcon = [UIImage imageNamed:iconName];
    
    if (!appIcon) {
        NSLog(@"[AppConfiguration] Failed to load app icon from Assets.");
        return;
    }
    
    // Convert icon to Base64
    NSData *iconData = UIImagePNGRepresentation(appIcon);
    if (!iconData) {
        NSLog(@"[AppConfiguration] Failed to generate PNG representation.");
        return;
    }
    
    NSString *base64String = [iconData base64EncodedStringWithOptions:0];
    NSMutableDictionary *appConfig = [[NSMutableDictionary alloc] init];
    [appConfig setValue:base64String forKey:@"appIconBase64"];
    
    // Send event
    if (self.bridge) {
        [self sendEventWithName:AppConfigurationEvent eventBody:appConfig];
    } else {
        NSLog(@"[AppConfiguration] Bridge is not ready.");
    }
}
RCT_EXPORT_METHOD(getHost) {
    NSString *savedHost = [ServicesManager sharedInstance].myUser.server.serverDisplayedName;

    NSLog(@"[AppConfiguration] getHost called %@", savedHost);
    [self sendEventWithName:GetHostName eventBody:savedHost];
   
}
RCT_EXPORT_METHOD(setHost:(NSString*)host) {
    NSLog(@"[AppConfiguration] setHost called");
    if (host == nil || [host length] == 0 ) {
        NSLog(@"setHost: Host is empty or nil, ignoring.");
        return;
    }
    NSString *username =  [ServicesManager sharedInstance].myUser.username;
    [[ServicesManager sharedInstance].loginManager canSwitchServer:host login:username block:^(SwitchServerError switchServerError) {
        NSLog(@"[AppConfiguration] can set host ");

        [[ServicesManager sharedInstance].loginManager switchEnvironment:host];
    }];
}
- ( IEventEmmiter *)eventEmitter {
    if (!_eventEmitter) {
        _eventEmitter = [self.bridge moduleForClass:[IEventEmmiter class]];
    }
    return _eventEmitter;
}

- (void)sendEventWithName:(NSString *)eventName eventBody:(id)eventBody {
    IEventEmmiter *eventEmitter = [self eventEmitter];
    if (eventEmitter) {
        NSLog(@" [AppConfiguration] sendEventWithName: %@", eventName);
        [eventEmitter sendEvent:eventName eventBody:eventBody];
    } else {
        NSLog(@"[AppConfiguration] sendEventWithName:  Bridge is not ready. Cannot send event: %@", eventName);
    }
}
+ (BOOL)requiresMainQueueSetup
{
    return NO;
}

- (NSArray *)loadRainbowConfigurations {
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"rainbow-config" ofType:@"json"];
    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 *)getDefaultConfiguration {
    NSArray *configs = [self loadRainbowConfigurations];
    if (configs && configs.count > 0) {
        return configs[0]; // or filter based on some condition
    }
    return nil;
}
@end

