//
//  DPCCrossSDK.m
//  DapiSDK
//
//  Created by MSZ on 11/11/2022.
//

#import "DPCCrossSDK.h"

@implementation UIViewController (VisibleViewController)
- (UIViewController *)visibleViewController {
    BOOL isNavigationController = [self isKindOfClass:[UINavigationController class]];
    BOOL isTabBarController = [self isKindOfClass:[UITabBarController class]];
    UIViewController *presentedViewController = self.presentedViewController;
    //    BOOL isAlertController = [self isKindOfClass:[UIAlertController class]];

    if (isNavigationController) {
        UINavigationController *navigationController = (UINavigationController *)self;
        return navigationController.topViewController.visibleViewController;
    } else if (isTabBarController) {
        UITabBarController *tabBarController = (UITabBarController *)self;
        return tabBarController.selectedViewController.visibleViewController;
    } else if (presentedViewController) {
        return self.presentedViewController.visibleViewController;
    }
    else {
        return self;
    }
}


@end

@implementation DPCCrossSDK

+ (UIViewController *)topViewController {
    return [UIApplication sharedApplication].delegate.window.rootViewController.visibleViewController;
}

+ (DAPIConfigurations *)setNativeConfigurations:(NSDictionary<NSString *, id> *)configs {
    NSArray *countries = [configs objectForKey:@"countries"];

    DAPIConfigurations *configurations = [[DAPIConfigurations alloc] init];
    configurations.showTransferErrorResult = YES;
    configurations.showLogos = YES;
    configurations.showTransferSuccessfulResult = YES;
    [DPC.sharedInstance setCountries: countries] ;
    [DPC.sharedInstance setConfigurations:configurations];
    NSDictionary<NSString *, id> *endPointExtraHeaderFields = [configs objectForKey:@"endPointExtraHeaderFields"];
    NSDictionary<NSString *, id> *endPointExtraBody = [configs objectForKey:@"endPointExtraBody"];

    if (endPointExtraHeaderFields) {
        [DPC.sharedInstance setEndpointExtraHeaderFields:@{DPCEndpointAll: endPointExtraHeaderFields}];
    }
    if (endPointExtraBody) {
        [DPC.sharedInstance setEndpointExtraBody:@{DPCEndpointAll: endPointExtraBody}];
    }
    NSNumber *showLogos = [configs objectForKey:@"showLogos"];
    NSNumber *showTransferSuccessfulResult = [configs objectForKey:@"showTransferSuccessfulResult"];
    NSNumber *showTransferErrorResult = [configs objectForKey:@"showTransferErrorResult"];

    if (showLogos != nil) {
        configurations.showLogos = showLogos.boolValue;
    }
    if (showTransferSuccessfulResult != nil) {
        configurations.showTransferSuccessfulResult = showTransferSuccessfulResult.boolValue;
    }

    if (showTransferErrorResult != nil) {
        configurations.showTransferErrorResult = showTransferErrorResult.boolValue;
    }
    
    NSDictionary<NSString *, NSString *> *themeDic = [configs objectForKey:@"theme"];
    if (themeDic == nil) { return configurations;}
    NSString *theme = [themeDic objectForKey:@"enforceTheme"];
    if (theme && [theme isEqualToString: @"light"]){
        [Dapi.shared.uiCustomization setTheme: DAPIThemeLight];
    } else if (theme &&  [theme isEqualToString: @"dark"]){
        [Dapi.shared.uiCustomization setTheme: DAPIThemeDark];
    } else {
        [Dapi.shared.uiCustomization setTheme: DAPIThemeDynamic];
    }
    NSDictionary<NSString *, NSString *> *primaryColor = [themeDic objectForKey:@"primaryColor"];
    if (primaryColor) {
        NSString *lightModeHexa = [primaryColor objectForKey:@"lightMode"];
        NSString *darkModeHexa = [primaryColor objectForKey:@"darkMode"];
        [Dapi.shared.uiCustomization.primaryColor setLightModeHexaCode:lightModeHexa];
        [Dapi.shared.uiCustomization.primaryColor setDarkModeHexaCode:darkModeHexa];
    }


    return configurations;
}



+ (NSDictionary<NSString *, id> *)jsConfigurations {
    NSString *environment = @"sandbox";
    if (Dapi.shared.environment == DAPIEnvironmentProduction ) {
        environment = @"production";
    }
    return @{
        @"countries": DPC.sharedInstance.countries ?: [NSNull null],
        @"environment": environment ?: [NSNull null],
        @"endPointExtraQueryItems":  @{@"":@[@""]},
        @"endPointExtraHeaderFields": DPC.sharedInstance.endpointExtraHeaderFields ?: [NSNull null],
        @"endPointExtraBody": DPC.sharedInstance.endpointExtraBody ?: [NSNull null],
        @"showCloseButton": [NSNumber numberWithBool: NO],
        @"showLogos": [NSNumber numberWithBool:Dapi.shared.configurations.showLogos],
        @"showAddButton": [NSNumber numberWithBool:NO],
        @"showTransferSuccessfulResult": [NSNumber numberWithBool:Dapi.shared.configurations.showTransferSuccessfulResult],
        @"showTransferErrorResult": [NSNumber numberWithBool:Dapi.shared.configurations.showTransferErrorResult]
    };

}
+ (DAPIBankConnection *)bankConnectionForUserID:(NSString *)userID {
    __block DAPIBankConnection *bankConnection;
    [DPC.sharedInstance.getConnections enumerateObjectsUsingBlock:^(DAPIBankConnection * _Nonnull obj,
                                                                    NSUInteger idx,
                                                                    BOOL * _Nonnull stop) {
        if ([obj.userID isEqualToString:userID]) {
            *stop = YES;
            bankConnection = obj;
        }
    }];
    return  bankConnection;
}

+ (NSString *)jsonRepresentationOfError:(NSError *)error
                                accountID:(NSString *)accountID
                            operationID:(NSString *)operationID {

    NSDictionary *jsonError = @{
        @"error": error.localizedDescription ?: [NSNull null],
        @"account": [[NSString alloc] initWithFormat:@"AccountID %@", accountID],
        @"operationID": operationID ?: [NSNull null]
    };

    NSError *convertingError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonError
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&convertingError];
    if (convertingError) {
        return [NSString stringWithFormat:@"{\"error\": %@, \"account\": null}", error.dapiErrorMessage];
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return jsonString;
    }
}

+ (DAPIBeneficiary *)nativeBeneficiaryInfoFromDictionary:(NSDictionary<NSString *,id> *)beneficiaryInfoDictionary {
    DAPIBeneficiary *beneficiary = [[DAPIBeneficiary alloc] init];
    NSDictionary<NSString *, id> *lineAddressDictionary = [beneficiaryInfoDictionary objectForKey:@"linesAddress"];
    DAPILineAddress *lineAddress = [[DAPILineAddress alloc] init];
    lineAddress.line1 = [lineAddressDictionary objectForKey:@"line1"];
    lineAddress.line2 = [lineAddressDictionary objectForKey:@"line2"];
    lineAddress.line3 = [lineAddressDictionary objectForKey:@"line3"];
    beneficiary.linesAddress =  lineAddress;
    beneficiary.accountNumber = [beneficiaryInfoDictionary objectForKey:@"accountNumber"];
    beneficiary.name = [beneficiaryInfoDictionary objectForKey:@"name"];
    beneficiary.bankName = [beneficiaryInfoDictionary objectForKey:@"bankName"];
    beneficiary.swiftCode = [beneficiaryInfoDictionary objectForKey:@"swiftCode"];
    beneficiary.iban = [beneficiaryInfoDictionary objectForKey:@"iban"];
    beneficiary.phoneNumber = [beneficiaryInfoDictionary objectForKey:@"phoneNumber"];
    beneficiary.country = [beneficiaryInfoDictionary objectForKey:@"country"];
    beneficiary.branchAddress = [beneficiaryInfoDictionary objectForKey:@"branchAddress"];
    beneficiary.branchName = [beneficiaryInfoDictionary objectForKey:@"branchName"];
    return beneficiary;
}

+ (DAPIWireBeneficiary *)nativeWireBeneficiaryInfoFromDictionary:(NSDictionary<NSString *,id> *)beneficiaryInfoDictionary {
    DAPIWireBeneficiary *beneficiary = [[DAPIWireBeneficiary alloc] init];
    NSDictionary<NSString *, id> *lineAddressDictionary = [beneficiaryInfoDictionary objectForKey:@"linesAddress"];
    DAPILineAddress *lineAddress = [[DAPILineAddress alloc] init];
    lineAddress.line1 = [lineAddressDictionary objectForKey:@"line1"];
    lineAddress.line2 = [lineAddressDictionary objectForKey:@"line2"];
    lineAddress.line3 = [lineAddressDictionary objectForKey:@"line3"];
    beneficiary.linesAddress = lineAddress;
    beneficiary.accountNumber = [beneficiaryInfoDictionary objectForKey:@"accountNumber"];
    beneficiary.name = [beneficiaryInfoDictionary objectForKey:@"name"];
    beneficiary.country = [beneficiaryInfoDictionary objectForKey:@"country"];
    beneficiary.receiverType = [beneficiaryInfoDictionary objectForKey:@"receiverType"];
    beneficiary.routingNumber = [beneficiaryInfoDictionary objectForKey:@"routingNumber"];
    beneficiary.nickname = [beneficiaryInfoDictionary objectForKey:@"nickname"];
    beneficiary.receiverAccountType = [beneficiaryInfoDictionary objectForKey:@"receiverAccountType"];
    beneficiary.firstName = [beneficiaryInfoDictionary objectForKey:@"firstName"];
    beneficiary.lastName = [beneficiaryInfoDictionary objectForKey:@"lastName"];
    beneficiary.zipCode = [beneficiaryInfoDictionary objectForKey:@"zipCode"];
    beneficiary.state = [beneficiaryInfoDictionary objectForKey:@"state"];
    beneficiary.city = [beneficiaryInfoDictionary objectForKey:@"city"];
    return beneficiary;
}

@end
