

//
//  MOLPayReactManager.m
//  MOLPayXDK
//
//  Created by Leow on 10/12/28 H.
//  Copyright © 28 Heisei Facebook. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "MOLPayReactManager.h"
#import <React/RCTBridgeModule.h>


#import "MOLPayLib.h"

//#import <React/RCTView.h>
//#import <React/RCTRootView.h>
//#include "MOLPayReactViewController.h"

@interface MOLPayReactManager() <MOLPayLibDelegate>
{
    MOLPayLib *mp;
    UINavigationController *navController;
}
@property (nonatomic, assign) BOOL isTaskCompleted;
@property (nonatomic, copy) RCTResponseSenderBlock callback;
@end

// MOLPayReactManager.m
@implementation MOLPayReactManager

RCT_EXPORT_MODULE(FiuuPayment);

RCT_EXPORT_METHOD(setPaymentDetails:(NSDictionary *)paymentDetails callback:(RCTResponseSenderBlock)callback)
{
    dispatch_sync(dispatch_get_main_queue(), ^{
        //        MOLPayReactViewController *mpvc = [[MOLPayReactViewController alloc] init];
        self.isTaskCompleted = NO;
        self.callback = callback;
        NSMutableDictionary *paymentDetailsMutable = [paymentDetails mutableCopy];
        
        [paymentDetailsMutable setObject:@"YES" forKey:@"is_submodule"];
        [paymentDetailsMutable setObject:@"molpay-mobile-xdk-reactnative-beta-ios" forKey:@"module_id"];
        [paymentDetailsMutable setObject:@"25rn" forKey:@"wrapper_version"];
        
        UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
        
        mp = [[[MOLPayLib alloc] init] initWithDelegate:self andPaymentDetails: paymentDetailsMutable];
        navController = [[UINavigationController alloc] initWithRootViewController:mp];
        navController.modalPresentationStyle = UIModalPresentationFullScreen;
        [window.rootViewController presentViewController:navController animated:NO completion:nil];
        [window makeKeyAndVisible];
    });
}

-(void)transactionResult:(NSDictionary *)result {
    NSLog(@"Payment result 2 %@", result);
    if (!self.isTaskCompleted) {
        self.isTaskCompleted = YES;
        self.callback(@[result]);
//        UIViewController *viewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
//        if ( viewController.presentedViewController && !viewController.presentedViewController.isBeingDismissed ) {
//            viewController = viewController.presentedViewController;
//        }
        [mp dismissViewControllerAnimated:YES completion:nil];
    }
}
@end