//
//  FastWechat.m
//  react-native-fast-wechat
//
//  Created by _sseon on 2024/3/30.
//

#import "FastWechat.h"
#import "WXApi.h"
#import "FastWechatDelegator.h"

@implementation FastWechat
{
    NSString *appId;
    NSNumber *isAppIDRegistered;
    NSNumber *hasListeners;
    NSNumber *isProcessPaying;
}

RCT_EXPORT_MODULE()

- (void)startObserving
{
    self->hasListeners = @1;
    [NSNotificationCenter.defaultCenter
     addObserver:self
     selector:@selector(handleOnResp:)
     name: FastWechatDelegator.event
     object:nil];
    [NSNotificationCenter.defaultCenter
    addObserver:self
     selector:@selector(handleDidBecomeActiveNotification:)
     name:UIApplicationDidBecomeActiveNotification 
     object:nil];
    
}

- (void)stopObserving
{
    self->hasListeners = @0;
    [NSNotificationCenter.defaultCenter
     removeObserver:self
     name:FastWechatDelegator.event
     object:nil];
}

- (NSArray<NSString *> *)supportedEvents
{
    return @[@"wechat"];
}

RCT_EXPORT_METHOD(init:(NSString *)appId 
                  universalLinks:(NSString *)universalLinks
                  withResolver:(RCTPromiseResolveBlock) resolve
                  withReject:(RCTPromiseRejectBlock) reject)
{
    if(appId == nil) {
        reject(@"-1",@"AppId Cannot Leave Empty",nil);
        return;
    }
    self->appId = appId;
    self->isAppIDRegistered = @1;
    dispatch_async(dispatch_get_main_queue(), ^{
        BOOL result = [WXApi registerApp:appId universalLink:universalLinks];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if(result) {
                resolve(@1);
            }else{
                reject(@"-1",@"Wechat SDK Failed At Initialize",nil);
            }
        });
    });
}

RCT_EXPORT_METHOD(pay:(NSDictionary *) params
                  withResolver:(RCTPromiseResolveBlock) resolve
                  withReject:(RCTPromiseRejectBlock) reject)
{
    if (self->isAppIDRegistered == nil || [self->isAppIDRegistered  isEqual: @0]) {
        reject(@"-1",@"Wechat SDK Uninitialized",nil);
    }else{
        self->isProcessPaying = @1;
        PayReq *req = [[PayReq alloc] init];
        req.partnerId = [params valueForKey:@"partnerId"];
        req.prepayId = [params valueForKey:@"prepayId"];
        req.package = @"Sign=WXPay";
        req.nonceStr = [params valueForKey:@"nonceStr"];
        NSString *tm = [params valueForKey:@"timestamp"];
        
        if(tm != nil) {
            req.timeStamp = (UInt32)[tm intValue];
        }
        req.sign = [params valueForKey:@"sign"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [WXApi sendReq:req completion:^(BOOL success) {}];
        });
    }
}

RCT_EXPORT_METHOD(isInstalled: (RCTPromiseResolveBlock) resolve withReject:(RCTPromiseRejectBlock) reject)
{
    if( [WXApi isWXAppInstalled]) {
        resolve(@1);
    }else{
        resolve(@0);
    }
}


+ (BOOL)requiresMainQueueSetup
{
    return NO;
}


-(void) handleOnResp: (NSNotification*) notification
{
    if(notification.userInfo != nil){
        self->isProcessPaying = @0;
        NSString *type = [notification.userInfo valueForKey:@"type"];
        if([type isEqualToString:@"pay"]) {
//            NSNumber *code = [notification.userInfo valueForKey:@"code"];
            if([self->hasListeners isEqualToNumber:@1]){
                [self sendEventWithName:@"wechat" body: notification.userInfo];
            }
        }
    }
}

-(void) handleDidBecomeActiveNotification: (NSNotification *)notification
{
    if([self->isProcessPaying isEqualToNumber:@1]){
        self->isProcessPaying = @0;
        [self sendEventWithName:@"wechat" body: @{@"type": @"pay",@"code": @-666}];
    }
}

@end
