//
//  JPSafeBrowser.m
//
//
//  Created by Balaganesh S on 01/06/17.
//
//

#import "JPSafeBrowser.h"
#import <JuspaySafeBrowser/JuspaySafeBrowser.h>

typedef void(^GodelPluginBlock)(Boolean status, NSError* _Nullable error, id _Nullable info);

@interface GodelViewController : UIViewController

@property (nonatomic, strong) JuspaySafeBrowser *browser;
@property (nonatomic, strong) BrowserParams *browserParams;
@property (nonatomic, strong) GodelPluginBlock callback;

@end

@implementation GodelViewController

- (instancetype)initWithBrowserParams:(BrowserParams *)browserParams callback:(GodelPluginBlock)callback
{
    self = [super init];
    if (self) {
        self.browser = [[JuspaySafeBrowser alloc] init];
        self.callback = callback;
        self.browserParams = browserParams;
        
        self.view.backgroundColor = [UIColor whiteColor];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"Close" style:UIBarButtonItemStyleDone target:self action:@selector(dismissGodelView)];
        item.tintColor = [UIColor blackColor];
        self.navigationItem.leftBarButtonItem = item;
    }
    return self;
}

- (void)dismissGodelView {
    [self.browser backButtonPressed];
}

- (void)viewDidLoad {
    if (@available(iOS 13.0, *)) {
        self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    // To check if the webview has already been added
    if (self.view.subviews.count == 0) {
        
        [self.browser startpaymentWithJuspayInView:self.view withParameters:self.browserParams callback:^(Boolean status, NSError * _Nullable error, id  _Nullable info) {
            self.callback(status, error, info);
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.browser = nil;
}

@end

@interface GodelNavigationController : UINavigationController

@end

@implementation GodelNavigationController

- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}

@end

@implementation JPSafeBrowser

- (void)JuspayStartPayment:(CDVInvokedUrlCommand*)command {

    NSString* callbackId = command.callbackId;
    NSDictionary *arguments = [[command arguments] objectAtIndex:0];
    NSDictionary *params = [arguments objectForKey:@"browserParams"];

    BrowserParams *browserParams = [[BrowserParams alloc] init];
    browserParams.url = [params objectForKey:@"url"];
    browserParams.merchantId = [params objectForKey:@"merchantId"];
    browserParams.clientId = [params objectForKey:@"clientId"];
    browserParams.transactionId = [params objectForKey:@"transactionId"];
    browserParams.orderId = [params objectForKey:@"orderId"];
    browserParams.amount = [params objectForKey:@"amount"];
    browserParams.customerEmail = [params objectForKey:@"customerEmail"];
    browserParams.endUrlRegexes = [arguments objectForKey:@"endUrlRegexes"];

    if([params objectForKey:@"postData"]) {
        browserParams.postData = [params objectForKey:@"postData"];
    }
    
    GodelViewController *godelViewController = [[GodelViewController alloc] initWithBrowserParams:browserParams callback:^(Boolean status, NSError * _Nullable error, id  _Nullable info) {
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        CDVPluginResult *result = nil;
        
        if (error && error.code != 101) {
            [dict setObject:error.description forKey:@"data"];
            
            result = [CDVPluginResult
                      resultWithStatus:CDVCommandStatus_ERROR
                      messageAsDictionary:dict];
        } else {
            
            NSMutableDictionary *pluginInfo = [[NSMutableDictionary alloc] initWithDictionary:info];
            [pluginInfo setObject:[pluginInfo valueForKey:@"EndUrl"] forKey:@"url"];
            [pluginInfo removeObjectForKey:@"EndUrl"];
            
            if(status == true) {
                [dict setObject:@"endUrlReached" forKey:@"_method"];
            } else {
                [dict setObject:@"onTransactionAborted" forKey:@"_method"];
            }
            [dict setObject:pluginInfo forKey:@"data"];
            
            result = [CDVPluginResult
                      resultWithStatus:CDVCommandStatus_OK
                      messageAsDictionary:dict];
        }
        [self.commandDelegate sendPluginResult:result callbackId:callbackId];
    }];

    GodelNavigationController *navigationController = [[GodelNavigationController alloc] initWithRootViewController:godelViewController];
    [navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor blackColor]}];
    navigationController.navigationBar.translucent = NO;
    navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    navigationController.modalPresentationStyle = UIModalPresentationFullScreen;

    [self.viewController presentViewController:navigationController animated:YES completion:nil];
}

@end
