//
//  RCTBraintree.m
//  RCTBraintree
//
//  Created by Jain, Mitesh on 10/20/16.
//  Copyright © 2016 Jain, Mitesh. All rights reserved.
//

#import "RCTBraintree.h"
#import "RCTUtils.h"
#import "RCTConvert.h"

@implementation RCTBraintree

//static NSString *URLScheme;
// you dont need this if you adding url scheme stuff to delegate directly
//+ (instancetype)sharedInstance {
//    NSLog(@"here");
//    static RCTBraintree *_sharedInstance = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        _sharedInstance = [[RCTBraintree alloc] init];
//    });
//    return _sharedInstance;
//}

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(initWithAuthorization:(NSString *)clientToken callback:(RCTResponseSenderBlock)callback)
{
    self.braintreeClient = [[BTAPIClient alloc] initWithAuthorization:clientToken];
    if (self.braintreeClient == nil) {
        callback(@[@false]);
    }
    else {
        callback(@[@true]);
    }
}

//RCT_EXPORT_METHOD(setupWithURLScheme:(NSString *)clientToken urlscheme:(NSString*)urlscheme callback:(RCTResponseSenderBlock)callback)
//{
//    URLScheme = urlscheme;
//    [BTAppSwitch setReturnURLScheme:urlscheme];
//    self.braintreeClient = [[BTAPIClient alloc] initWithAuthorization:clientToken];
//    if (self.braintreeClient == nil) {
//        callback(@[@false]);
//    }
//    else {
//        callback(@[@true]);
//    }
//}


RCT_EXPORT_METHOD(dropInViewController:(NSDictionary *)options callback:(RCTResponseSenderBlock)callback)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        BTDropInViewController *dropInViewController = [[BTDropInViewController alloc] initWithAPIClient:self.braintreeClient];
        dropInViewController.delegate = self;
        
        NSLog(@"%@", options);
        
        UIColor *tintColor = options[@"tintColor"];
        UIColor *bgColor = options[@"bgColor"];
        UIColor *barBgColor = options[@"barBgColor"];
        UIColor *barTintColor = options[@"barTintColor"];
        
        if (tintColor) dropInViewController.view.tintColor = [RCTConvert UIColor:tintColor];
        if (bgColor) dropInViewController.view.backgroundColor = [RCTConvert UIColor:bgColor];
        
        dropInViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(userDidCancelPayment)];
        
        self.callback = callback;
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:dropInViewController];
        
        if (barBgColor) navigationController.navigationBar.barTintColor = [RCTConvert UIColor:barBgColor];
        if (barTintColor) navigationController.navigationBar.tintColor = [RCTConvert UIColor:barTintColor];
        
        if(options[@"paymentControllertitle"]){
            navigationController.navigationBar.topItem.title = options[@"paymentControllertitle"];
        }
        else{
            navigationController.navigationBar.topItem.title = @"Payment Options";
        }

        if (options[@"submitButtonTitle"]) {
            BTPaymentRequest *paymentRequest = [[BTPaymentRequest alloc] init];
            paymentRequest.callToActionText = options[@"submitButtonTitle"];
            
            dropInViewController.paymentRequest = paymentRequest;
        }
        
        self.reactNativeController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        [self.reactNativeController presentViewController:navigationController animated:YES completion:nil];
    });
}

RCT_EXPORT_METHOD(payPalViewController:(RCTResponseSenderBlock)callback)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        BTPayPalDriver *payPalDriver = [[BTPayPalDriver alloc] initWithAPIClient:self.braintreeClient];
        payPalDriver.viewControllerPresentingDelegate = self;
        
        [payPalDriver authorizeAccountWithCompletion:^(BTPayPalAccountNonce *tokenizedPayPalAccount, NSError *error) {
            NSArray *args = @[];
            if ( error == nil ) {
                args = @[[NSNull null], tokenizedPayPalAccount.nonce, tokenizedPayPalAccount.email, tokenizedPayPalAccount.firstName, tokenizedPayPalAccount.lastName, tokenizedPayPalAccount.phone];
            } else {
                args = @[error.description, [NSNull null]];
            }
            callback(args);
        }];
    });
}

// dont need this if we using the method in delegate
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//    
//    if ([url.scheme localizedCaseInsensitiveCompare:URLScheme] == NSOrderedSame) {
//        return [BTAppSwitch handleOpenURL:url sourceApplication:sourceApplication];
//    }
//    return NO;
//}


RCT_EXPORT_METHOD(getCardNonce: (NSString *)cardNumber
                  expirationMonth: (NSString *)expirationMonth
                  expirationYear: (NSString *)expirationYear
                  cvv: (NSString *)cvv
                  callback: (RCTResponseSenderBlock)callback
                  )
{
    BTCardClient *cardClient = [[BTCardClient alloc] initWithAPIClient: self.braintreeClient];
    BTCard *card = [[BTCard alloc] initWithNumber:cardNumber expirationMonth:expirationMonth expirationYear:expirationYear cvv:cvv];
    
    [cardClient tokenizeCard:card
                  completion:^(BTCardNonce *tokenizedCard, NSError *error) {
                      
                      NSArray *args = @[];
                      if ( error == nil ) {
                          args = @[[NSNull null], tokenizedCard.nonce];
                      } else {
                          args = @[error.description, [NSNull null]];
                      }
                      callback(args);
                  }
     ];
}

#pragma mark - BTDropInViewControllerDelegate

- (void)userDidCancelPayment {
    [self.reactNativeController dismissViewControllerAnimated:YES completion:nil];
    self.callback(@[@"userDidCancelPayment", [NSNull null]]);
}

- (void)dropInViewController:(BTDropInViewController *)viewController didSucceedWithTokenization:(BTPaymentMethodNonce *)paymentMethodNonce {
//     Send payment method nonce to your server for processing
//    [self postNonceToServer:paymentMethodNonce.nonce];
    self.callback(@[[NSNull null],paymentMethodNonce.nonce]);
    [viewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)dropInViewControllerDidCancel:(__unused BTDropInViewController *)viewController {
    [viewController dismissViewControllerAnimated:YES completion:nil];
    self.callback(@[@"dropInViewControllerDidCancel", [NSNull null]]);

}

#pragma mark - BTViewControllerPresentingDelegate

- (void)paymentDriver:(id)paymentDriver requestsPresentationOfViewController:(UIViewController *)viewController {
    self.reactNativeController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    [self.reactNativeController presentViewController:viewController animated:YES completion:nil];
}

- (void)paymentDriver:(id)paymentDriver requestsDismissalOfViewController:(UIViewController *)viewController {
    self.reactNativeController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
    [self.reactNativeController dismissViewControllerAnimated:YES completion:nil];
}


@end
