
#import "RNPaymentSdk.h"

@implementation RNPaymentSdk

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
RCT_EXPORT_MODULE()

////////////////////////////////////MOMO//////////////////////////////////
RCT_EXPORT_METHOD(rechargeMomo:(double)amount withfee:(double)fee
                  withUserName:(NSString *)userName withBundleID:(NSString*)bundleID
                  withMerchantCode:(NSString*)merchantCode withMerchantID:(NSString*)merchantID
                  withMerchantName:(NSString*)merchantName withMerchantNameLabel:(NSString*)merchantNameLabel
                  withMerchantPublicKey:(NSString*) merchantPublicKey
                  resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)  {
    
    self.amount = amount;
    //
 
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NoficationCenterTokenReceived:)
                                                 name:@"NoficationCenterTokenReceived"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NoficationCenterCreateOrderReceived:)
                                                 name:@"NoficationCenterCreateOrderReceived"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(NoficationCenterStartRequestToken:)
                                                 name:@"NoficationCenterStartRequestToken"
                                               object:nil];
    
    self.resolveMoMo = resolve;
    self.rejectMoMo = reject;
    //init MOMO
  
    [MoMoPaySDK initializingAppBundleId:bundleID merchantCode:merchantCode merchantName:merchantName merchantNameLabel:merchantID merchantPublicKey:merchantPublicKey];
    
    
    NSMutableDictionary *paymentInfo = [[NSMutableDictionary alloc]init];
    paymentInfo[MOMO_PAY_CLIENT_MERCHANT_TRANS_ID] = merchantID;
    paymentInfo[MOMO_PAY_CLIENT_AMOUNT_TRANSFER] = [NSString stringWithFormat:@"%f",amount];
    paymentInfo[MOMO_PAY_CLIENT_FEE_TRANSFER] = [NSString stringWithFormat:@"%f",fee];
    paymentInfo[MOMO_PAY_CLIENT_USERNAME] = userName;

    
     NSURL *url = [[NSURL alloc]initWithString:@"com.mservice.com.vn.MoMoTransfer://"];
    
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        [[MoMoPayment shareInstant] createPaymentInformation:paymentInfo];
        [[MoMoPayment shareInstant] setAction:MOMO_PAY_SDK_ACTION_GETTOKEN];
        [[MoMoPayment shareInstant] requestToken];
        
        resolve(@"1");
    } else {
        
        NSString *domain = @"com.hides.paymentSDK";
        NSString *desc = NSLocalizedString(@"Thanh toán Momo thất bại.", @"");
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
        
        NSError *error = [NSError errorWithDomain:domain
                                             code:-101
                                         userInfo:userInfo];
        reject(@"-1",@"Thanh toán Momo thất bại.",error);

        
    }


}
//MARK: Handle response MoMo payment
-(NSMutableDictionary*) getDictionaryFromComponents:(NSArray*) components{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
     // parse parameters to dictionary
    for(NSString *param in components){
        NSArray *elts = [param componentsSeparatedByString:@"="];
        if ([elts count] < 2){
            continue;
        }
         // get key,value
        NSString * key = elts[0];
        key = [key stringByReplacingOccurrencesOfString:@"?" withString:@""];
        NSString *value = elts[1];
        ///Start Fix HTML Property issue
        
        if ([elts count] > 2){
            NSUInteger range = [param rangeOfString:@"="].location;
            if ((range + 1) < [param length]){
                value = [param substringFromIndex:range + 1];
            }
        }
        value = [NSString stringWithCString:[value UTF8String] encoding:NSUTF8StringEncoding];
        if ([value length] > 0 && [key length] > 0){
            params[key] = value;
        }
        
    }
    return params;
}
-(NSMutableDictionary *)getDictionaryFromMomoPaymentInfo:(NSNotification *)notif{
    NSMutableDictionary * result = [[NSMutableDictionary alloc]init];
    if([notif object] != NULL){
        if([[notif object] isKindOfClass:[NSString class]]){
            NSString * data = [notif object];
            NSString *sourceText = [data stringByReplacingOccurrencesOfString:@"vn.vuiphattai.lotto://?" withString:@""];
            sourceText = [sourceText stringByReplacingOccurrencesOfString:@"vn.vuiphattai.lotto" withString:@""];
            sourceText = [sourceText stringByReplacingOccurrencesOfString:@"://://" withString:@"://"];
            NSArray *components = [sourceText componentsSeparatedByString:@"&"];
            
            result = [self getDictionaryFromComponents:components];
        }
        
    }
    return result;
}

-(void)NoficationCenterTokenReceived:(NSNotification*) notif{
    NSMutableDictionary * result = [self getDictionaryFromMomoPaymentInfo:notif];
    
    NSString *status = [result objectForKey:@"status"];
    NSString *mess = [result objectForKey:@"message"];
  
    
    NSMutableDictionary * contentDictionary = [[NSMutableDictionary alloc]init];
    contentDictionary[@"phone"] = [result objectForKey:@"phonenumber"];
    contentDictionary[@"app_data"] = [result objectForKey:@"data"];
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:contentDictionary // Here you can pass array or dictionary
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    NSString *jsonString;
    if (jsonData) {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        self.resolveMoMo(jsonString);
    } else {
        
        NSString *domain = @"com.hides.paymentSDK";
        NSString *desc = NSLocalizedString(mess, @"");
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
        
        NSError *error = [NSError errorWithDomain:domain
                                             code:-101
                                         userInfo:userInfo];
        self.rejectMoMo(status,mess,error);

    }
    
}
-(void)NoficationCenterCreateOrderReceived:(NSNotification*) notif{
    NSMutableDictionary *response = [notif object];
    NSString *status = [response objectForKey:@"status"];
    
    if(![status isEqualToString:@"0"]){
        NSString *mess = [response objectForKey:@"message"];
        mess = (mess == NULL) ? @"Thanh toán Momo thất bại." : mess;
        NSString *domain = @"com.hides.paymentSDK";
        NSString *desc = NSLocalizedString(mess, @"");
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
        
        NSError *error = [NSError errorWithDomain:domain
                                             code:-101
                                         userInfo:userInfo];
        self.rejectMoMo(status,mess,error);

    }
}

-(void)NoficationCenterStartRequestToken:(NSNotification*) notif{
    [[MoMoPayment shareInstant] updateAmount:self.amount];
}

////////////////////////////////////////////ZALOPAY/////////////////////////////////
/*RCT_EXPORT_METHOD(rechargeZaloPay:(NSString *)appID withTransToken:(NSString*)token
                  resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)  {
    
    self.resolveZaloPay = resolve;
    self.rejectZaloPay = reject;
    //init zalopay
    [[ZaloPaySDK sharedInstance] initWithAppId:42];
    
    //
    [ZaloPaySDK sharedInstance].delegate = self;
    [[ZaloPaySDK sharedInstance] payOrder:token];
    
}

-(void)zalopayCompleteWithErrorCode:(ZPErrorCode)errorCode transactionId:(NSString *)transactionId{
    
    if (errorCode == ZPErrorCode_Success){
        self.resolveZaloPay(@"1");
    }
    else{
        NSString *mess = [self zalopayMessage:errorCode];
        NSString *domain = @"com.hides.paymentSDK";
        NSString *desc = NSLocalizedString(mess, @"");
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : desc };
        
        NSError *error = [NSError errorWithDomain:domain
                                             code:-101
                                         userInfo:userInfo];
        NSString *errorCode_ = [NSString stringWithFormat:@"%ld",(long)errorCode];
        self.rejectZaloPay(errorCode_,mess,error);

    }
}


-(NSString *)zalopayMessage:(ZPErrorCode)code{
 
    switch (code) {
        case ZPErrorCode_Success:
            return @"Nạp tiền qua ZaloPay thành công";
        case ZPErrorCode_NotInstall:
            return @"Ứng dụng zalopay chưa được cài dặt trên thiết bị";

        case ZPErrorCode_InvalidResponse:
            return @"Không nhận được phản hồi từ Zalopay";

        case ZPErrorCode_InvalidOrder:
            return @"Giao dịch không hơp lệ. Vui lòng thử lại sau";

        case ZPErrorCode_UserCancel:
            return @"Giao dich ZaloPay đã được huỷ";
        case ZPErrorCode_Fail:
            return @"Hệ thống đang có lỗi, vui lòng quay lại sau";
            
        default:
            return @"Hệ thống đang có lỗi, vui lòng quay lại sau";
            break;
    }
}*/

@end
