//
//  TrusteeHelpCrunch.m
//  TrusteeHelpCrunch
//
//  Created by yurdjan on 16.01.2025.
//


#import "TrusteeHelpCrunch.h"
#import <React/RCTLog.h>
#import <HelpCrunchSDK/HelpCrunch.h>

@implementation TrusteeHelpCrunch
RCT_EXPORT_MODULE()

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

+ (void)initialize:(nonnull NSString *)forOrganization withApplicationId:(nonnull NSString *)applicationId withSecret:(nonnull NSString *) applicationSecret {
    
    HCSConfiguration *configuration =
    [HCSConfiguration configurationForOrganization:forOrganization
                                     applicationId:applicationId
                                 applicationSecret:applicationSecret];
    
    [HelpCrunch registerForRemoteNotifications];

    [HelpCrunch initWithConfiguration:configuration
                                 user:nil
                           completion:^(NSError * _Nullable error) {
            NSLog(@"End of SDK initialization");
    }];
    
}

+ (void) callbackAfterInit:(nonnull NSDictionary *)userInfo {
    if (![HelpCrunch didReceiveRemoteNotification:userInfo]) {
    // this push notification does not belong to HelpCrunch
    }
}

#pragma mark - HelpCrunch presentation

RCT_EXPORT_METHOD(presentHelpCrunch:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject)
{
//    RCTPresentedViewController()
    [HelpCrunch showFromController:nil completion:^(NSError * _Nullable error) {
    // If you need to do something on completion of SDK view controller presenting
    }];
    resolve(@(YES));
}

RCT_EXPORT_METHOD(updateUser:(NSDictionary *)attributesDict
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)rejecter) {
    
    HCSUser *user = [HCSUser new];
    
    if (attributesDict[@"email"]) {
        user.email = attributesDict[@"email"];
    }
    
    if (attributesDict[@"userId"]) {
        user.userId = attributesDict[@"userId"];
    }
    
    if (attributesDict[@"name"]) {
        user.name = attributesDict[@"name"];
    }
    
    if (attributesDict[@"phone"]) {
        user.phone = attributesDict[@"phone"];
    }
    
    if (attributesDict[@"customData"]) {
        user.customData = attributesDict[@"customData"];
    }

    [HelpCrunch updateUser:user completion:^(NSError * _Nullable error) {
//        rejecter(@(NO));
    }];
    resolve(@(YES));
};


RCT_EXPORT_METHOD(trackEvent:(NSString *)eventName params:(NSDictionary *)eventParams)
{
    [HelpCrunch trackEvent:eventName data:eventParams];
}

RCT_EXPORT_METHOD(logout:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    [HelpCrunch logoutWithCompletion:^(NSError * _Nullable error) {}];
    resolve(@(YES));
}

RCT_EXPORT_METHOD(registerForNotifications)
{
    [HelpCrunch registerForRemoteNotifications];
}

RCT_EXPORT_METHOD(setTokenToHelpCrunch:(NSString *)deviceToken)
{
    [HelpCrunch setDeviceToken:deviceToken];
}

+ (void)setDeviceToken:(nonnull NSData *)deviceToken {
    [HelpCrunch setDeviceToken:deviceToken];
    NSLog(@"setDeviceToken");
}

RCT_EXPORT_METHOD(getNumberOfUnreadChats:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
    @try {
        NSUInteger count = [HelpCrunch numberOfUnreadChats];
        resolve(@(count));
    } @catch (NSException *exception) {
        resolve(nil);
    }
}

RCT_EXPORT_METHOD(setThemeConfiguration:(NSDictionary *)themeConfiguration)
{

    HCSTheme *theme = [themeConfiguration[@"currentTheme"] isEqual: @"dark"] ? [HelpCrunch darkTheme] : [HelpCrunch lightTheme];
    
    if (themeConfiguration[@"mainColor"] != nil) {
        theme.mainColor = [self colorFromHexString:[RCTConvert NSString:themeConfiguration[@"mainColor"]]];
    }
    
    if (themeConfiguration[@"themeConfig"] != nil) {
        for (NSString* themeKey in themeConfiguration[@"themeConfig"]) {
            if ([themeKey isEqualToString:@"preChatThemeConfig"]) {
                theme.prechatForm = [self setPreChatTheme:themeConfiguration[@"themeConfig"][themeKey]];
            }

            if ([themeKey isEqualToString:@"chatThemeConfig"]) {
                theme.chats = [self setChatTheme:themeConfiguration[@"themeConfig"][themeKey]];
            }

            if ([themeKey isEqualToString:@"navigationBarThemeConfig"]) {
                theme.navigationBar = [self setNavigationBarTheme:themeConfiguration[@"themeConfig"][themeKey]];
            }

            if ([themeKey isEqualToString:@"sendMessageThemeConfig"]) {
                theme.sendMessageArea = [self setSendMessageAreaTheme:themeConfiguration[@"themeConfig"][themeKey]];
            }
        }
    }

    [HelpCrunch bindTheme:theme];
}

- (HCSThemePrechatForm *) setPreChatTheme:(NSDictionary *)themeProperties {
    HCSThemePrechatForm *prechatTheme = [HelpCrunch lightTheme].prechatForm;
    for (NSString* configKey in themeProperties) {
        if ([themeProperties[configKey] isKindOfClass:[NSString class]] && [themeProperties[configKey] hasPrefix:@"#"]) { // this is supposed to be a color
            [prechatTheme setValue:[self colorFromHexString:[RCTConvert NSString:themeProperties[configKey]]] forKey:configKey];
        } else {
            [prechatTheme setValue:themeProperties[configKey] forKey:configKey];
        }
    }
    return prechatTheme;
}

- (HCSThemeChats *) setChatTheme:(NSDictionary *)themeProperties {
    HCSThemeChats *chatTheme = [HelpCrunch lightTheme].chats;
    for (NSString* configKey in themeProperties) {
        NSLog(@"configKey %@", configKey);
        if ([themeProperties[configKey] isKindOfClass:[NSString class]] && [themeProperties[configKey] hasPrefix:@"#"]) { // this is supposed to be a color
            [chatTheme setValue:[self colorFromHexString:[RCTConvert NSString:themeProperties[configKey]]] forKey:configKey];
        } else {
            [chatTheme setValue:themeProperties[configKey] forKey:configKey];
        }
    }
    NSLog(@"chatTheme %@", chatTheme);
    return chatTheme;
}

- (HCSThemeNavigationBar *) setNavigationBarTheme:(NSDictionary *)themeProperties {
    HCSThemeNavigationBar *navigationBarTheme = [HelpCrunch lightTheme].navigationBar;
    for (NSString* configKey in themeProperties) {
        if ([themeProperties[configKey] isKindOfClass:[NSString class]] && [themeProperties[configKey] hasPrefix:@"#"]) { // this is supposed to be a color
            [navigationBarTheme setValue:[self colorFromHexString:[RCTConvert NSString:themeProperties[configKey]]] forKey:configKey];
        } else {
            [navigationBarTheme setValue:themeProperties[configKey] forKey:configKey];
        }
    }
    return navigationBarTheme;
}

- (HCSThemeSendMessageArea *) setSendMessageAreaTheme:(NSDictionary *)themeProperties {
    HCSThemeSendMessageArea *sendMessageAreaTheme = [HelpCrunch lightTheme].sendMessageArea;
    for (NSString* configKey in themeProperties) {
        if ([themeProperties[configKey] isKindOfClass:[NSString class]] && [themeProperties[configKey] hasPrefix:@"#"]) { // this is supposed to be a color
            [sendMessageAreaTheme setValue:[self colorFromHexString:[RCTConvert NSString:themeProperties[configKey]]] forKey:configKey];
        } else {
            [sendMessageAreaTheme setValue:themeProperties[configKey] forKey:configKey];
        }
    }
    return sendMessageAreaTheme;
}

- (UIColor *)colorFromHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1];
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

@end

