//
//  ViewController.m
//  payBANGK
//
//  Created by Orboroi on 7/10/16.
//  Copyright © 2016 NSDB. All rights reserved.
//

#import "ViewController.h"
@import AddressBook;

@interface ViewController ()
- (void)verifyEmail;
- (void)backFromWebUrl;
@end

@implementation ViewController

NSString *startPage = @"0";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _webView.delegate = self;
    
    _webView.backgroundColor = [UIColor clearColor];
    _webView.opaque=NO;
    
    NSString *userHash = [self getUserHash];
    NSLog(@"userHash= %@\n\n", userHash);
    //NSString *html = [self getHtmlFromTemplate:@"index"];
    

    @try {
        NSString *emailaddress = [self getUserData:@"emailaddress"];
        if(emailaddress==NULL){
            emailaddress = @"";
            [self saveUserData:@"emailaddress" : emailaddress];
            NSLog(@"emailaddress= %@\n", emailaddress);
        }
    }
    @catch (NSException * e) {
        NSString *emailaddress = @"";
        [self saveUserData:@"emailaddress" : emailaddress];
        NSLog(@"emailaddress= %@\n", emailaddress);
    }
    @finally {
        
    }
    @try {
        NSString *member_hash = [self getUserData:@"member_hash"];
        if(member_hash==NULL){
            member_hash = @"";
            [self saveUserData:@"member_hash" : member_hash];
            NSLog(@"member_hash= %@\n", member_hash);
        }
    }
    @catch (NSException * e) {
        NSString *member_hash = @"";
        [self saveUserData:@"member_hash" : member_hash];
        NSLog(@"member_hash= %@\n", member_hash);
    }
    @finally {
        
    }
    
    NSString *phoneNumber = @"";
    [self saveUserData:@"phoneNumber" : phoneNumber];
    NSLog(@"phoneNumber= %@\n", phoneNumber);
    
    NSString *simSerialNumber = @"";
    [self saveUserData:@"simSerialNumber" : simSerialNumber];
    NSLog(@"simSerialNumber= %@\n", simSerialNumber);
    
    NSString *uniqueIdentifier = [NSProcessInfo processInfo].globallyUniqueString;
    [self saveUserData:@"deviceId" : uniqueIdentifier];
    NSLog(@"deviceId= %@\n", uniqueIdentifier);

    NSString *deviceType = @"iPhone";
    if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ deviceType = @"iPad"; }
    [self saveUserData:@"deviceType" : deviceType];

    NSString * appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    [self saveUserData:@"versionName" : appVersionString];
    NSLog(@"versionName= %@\n", appVersionString);
    
    NSString *versionCode = @"";
    [self saveUserData:@"versionCode" : versionCode];
    NSLog(@"versionCode= %@\n", versionCode);
    
    //NSLog(@"getApplicationPath= %@\n\n", [self getApplicationPath]);
    [self.webView loadHTMLString:[self getHtmlFromTemplate:@"index"]  baseURL:[self baseUrl]];
    //[self.webView loadHTMLString:[self getHtmlFromVocaPass:strURL]  baseURL:[self baseUrl]];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)backFromWebUrl{
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *backFromWebUrl = [myUserDefaults objectForKey:@"backFromWebUrl"];
    NSLog(@"backFromWebUrl= %@\n\n", backFromWebUrl);
    NSURL *url = [NSURL URLWithString:backFromWebUrl];
    startPage = [self getQueryStringValueFromUrl:url :@"page"];
    NSLog(@"startPage= %@\n\n", startPage);
}
- (void)verifyEmail{
    NSString *verification_url = [self getVerificationUrl];
    NSLog(@"verification_url= %@\n\n", verification_url);
    NSURL *url = [NSURL URLWithString:verification_url];
    
    //NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
    //[self.webView loadRequest: urlrequest];
    
    NSString *query = [url query];
    NSArray *components = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    for (NSString *component in components) {
        NSArray *subcomponents = [component componentsSeparatedByString:@"="];
        [parameters setObject:[[subcomponents objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                       forKey:[[subcomponents objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    NSLog(@"query= %@\n\n", parameters );
    NSString *account_hash = [parameters objectForKey:@"account_hash"];
    [self saveUserHash:account_hash];
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"account_hash = '%@';", account_hash ]];
    [self showHomeScreen];
    
}

- (NSString *) getQueryStringValueFromUrl:(NSURL*)url :(NSString*)forKey{
    NSString *query = [url query];
    NSArray *components = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    for (NSString *component in components) {
        NSArray *subcomponents = [component componentsSeparatedByString:@"="];
        [parameters setObject:[[subcomponents objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
                       forKey:[[subcomponents objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    NSLog(@"query= %@\n\n", parameters );
    NSString *value = [parameters objectForKey:forKey];
    NSLog(@"query %@ = %@\n\n", forKey, value );
    return value;
}

- (NSString *) getVerificationUrl{
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *verification_url = [myUserDefaults objectForKey:@"verification_url"];
    return verification_url;
    
}

- (NSString *) getUserHash{
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *hash = [myUserDefaults objectForKey:@"user_hash"];
    return hash;
    
}

- (void) saveUserHash:(NSString *)hash {
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    [myUserDefaults setObject: hash forKey: @"user_hash"];
}

- (NSString *) getUserData:(NSString *)key{
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    NSString *hash = [myUserDefaults objectForKey:key];
    return hash;
    
}

- (void) saveUserData:(NSString *)key :(NSString *)value {
    NSUserDefaults *myUserDefaults = [NSUserDefaults standardUserDefaults];
    [myUserDefaults setObject: value forKey: key];
}


int imageNo = 1;
NSString *transaction_session_hash = @"";
NSString *filename = @"";
NSString *filePath = @"";
UIImage *selectedImage = nil;
NSString *mediaAction = @"selectPhoto";

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    //imageNo++;
    
    //UIImage *chosenImage = info[UIImagePickerControllerEditedImage];
    UIImage *chosenImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    //NSLog(@"picker.sourceType= %d\n\n", picker.sourceType );
    //NSLog(@"picker.sourceType= %d\n\n", UIImagePickerControllerSourceTypeCamera );
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera){
        //chosenImage = [UIImage imageWithCGImage:chosenImage.CGImage scale:1.0 orientation:UIImageOrientationRight];
        chosenImage = [self scaleAndRotateImage:chosenImage];
        
    }
    //self.imageView.image = chosenImage;
    selectedImage = chosenImage;
    
    NSData * imageData = UIImagePNGRepresentation(chosenImage);
    //NSLog(@"imageData= %@\n\n", imageData );
    
    filename = [[NSString alloc] initWithFormat:@"%d", imageNo];
    filename = [filename stringByAppendingString:PHOTO_NAME];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    filePath = [docsDirectory stringByAppendingPathComponent:filename];
    NSError *error = nil;
    
    if([fileManager fileExistsAtPath:filePath]){
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
    }
    
    if(![fileManager fileExistsAtPath:filePath]){
        [imageData writeToFile:filePath atomically:YES];
    }
    
    //[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(chosenImage) forKey:filename];
    
    // NSData* data = [[NSUserDefaults standardUserDefaults]objectForKey:filename];
    //NSLog(@"data= %@\n\n", data );
    
    NSString *urlString = [SITE_SCHEMA stringByAppendingString: @"://showSelectedImage"];
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
    NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest: urlrequest];
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
}

- (UIImage *) scaleAndRotateImage: (UIImage *)image
{
    int kMaxResolution = 3000; // Or whatever
    
    CGImageRef imgRef = image.CGImage;
    
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);
    if (width > kMaxResolution || height > kMaxResolution) {
        CGFloat ratio = width/height;
        if (ratio > 1) {
            bounds.size.width = kMaxResolution;
            bounds.size.height = bounds.size.width / ratio;
        }
        else {
            bounds.size.height = kMaxResolution;
            bounds.size.width = bounds.size.height * ratio;
        }
    }
    
    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef),      CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;
    switch(orient)
    {
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;
            
        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;
            
        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    }
    
    UIGraphicsBeginImageContext(bounds.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft)
    {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    }
    else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }
    
    CGContextConcatCTM(context, transform);
    
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return imageCopy;
}

UIAlertView *progressDialog;
- (void)showProgressDialog:(NSString *)title{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hideProgressDialog];
        [self hideConfirmDialog];
        progressDialog = nil;
        if(progressDialog == nil){
            progressDialog = [[UIAlertView alloc] initWithTitle:title message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil]; //display without any btns
            
            UIView *indicatorView = [[UIView alloc] initWithFrame:CGRectMake(83,0,100,50)];
            
            UIActivityIndicatorView *loadingIndicator = [[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(50, 10, 37, 37)];
            loadingIndicator.center = indicatorView.center;
            loadingIndicator.hidesWhenStopped = true;
            loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
            [loadingIndicator startAnimating];
            [indicatorView addSubview:loadingIndicator];
            
            if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
                [progressDialog setValue:indicatorView forKey:@"accessoryView"]; //works only in iOS7
                indicatorView.center = self.view.center;
                [loadingIndicator startAnimating];
            } else {
                progressDialog.message = @"\n"; //or just add \n to the end of the message (it's a workaround to create space inside the alert view
                [progressDialog addSubview:indicatorView];
                indicatorView.center = self.view.center;
                [loadingIndicator startAnimating];
            }
            [progressDialog show];
        }
        else{
            [progressDialog setTitle:title ];
        }
    });
    
}
- (void)hideProgressDialog{
    if(progressDialog != nil){
        [progressDialog dismissWithClickedButtonIndex:0 animated:YES];
    }
}


NSString *confirmFor = @"confirm";
UIAlertView *confirmDialog;

- (void) confirm:(NSString *)type : (NSString *)title{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self hideProgressDialog];
        
        confirmDialog = [[UIAlertView alloc] initWithTitle:nil message:title delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles: @"OK", nil]; //to display with cancel btn
        
        
        confirmFor = type;
        
        [confirmDialog show];
    });
}
- (void)hideConfirmDialog{
    if(confirmDialog != nil){
        [confirmDialog dismissWithClickedButtonIndex:0 animated:YES];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(alertView == showAlertDialog){
        if ( buttonIndex == 0){
            //NSLog(@"Cancel: %@", detailString);
            if(![showAlertDialogCallback isEqualToString:@""]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@();", showAlertDialogCallback ]];
            }
        }
    }
    else if(alertView == confirmDialog){
        NSString* type = confirmFor;
        //NSString* detailString = [confirmDialog textFieldAtIndex:0].text;
        //NSLog(@"String is: %@", detailString);
        if ( buttonIndex == 0){
            //NSLog(@"Cancel: %@", detailString);
            if([type isEqualToString:@"ConfirmAccountVerification"]){
                
            }
            else if([type isEqualToString:@"confirmInviteToPAYYAPNow"]){
                
            }
            else if([type isEqualToString:@"confirmRefundThisTransaction"]){
                
            }
            else if([type isEqualToString:@"confirmAutoCompletePaymentInBackground"]){
                
            }
            else if([type isEqualToString:@"confirmSelectOption"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"confirmSelectOption('no');" ]];
            }
        }
        if (buttonIndex == 1) {
            //NSLog(@"Ok : %@", detailString);
            if([type isEqualToString:@"ConfirmAccountVerification"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showVerificationForm('%@');", [self getUserHash] ]];
            }
            else if([type isEqualToString:@"confirmInviteToPAYYAPNow"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"openContact('%@');", @"tell_friends_form" ]];
            }
            else if([type isEqualToString:@"confirmRefundThisTransaction"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"confirmRefundThisTransaction();" ]];
            }
            else if([type isEqualToString:@"confirmAutoCompletePaymentInBackground"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"confirmAutoCompletePaymentInBackground();" ]];
            }
            else if([type isEqualToString:@"confirmSelectOption"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"confirmSelectOption('yes');" ]];
            }
        }
    }
}

UIAlertView *showAlertDialog;
NSString *showAlertDialogCallback = @"";
-(void)showAlert:(NSString *)type :(NSString *)msg :(NSString *)callback{
    [self hideProgressDialog];
    [self hideConfirmDialog];
    showAlertDialogCallback = callback;
    showAlertDialog = [[UIAlertView alloc] initWithTitle:type
                                                          message:msg
                                                         delegate:self
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles: nil];
    
    [showAlertDialog show];
}

-(void)showAlert:(NSString *)msg{
    [self hideProgressDialog];
    [self hideConfirmDialog];
    [self showAlert:nil:msg:@""];
}

- (void)watchYoutTubeVideo:(NSString*)id{
    NSURL *linkToApp = [NSURL URLWithString:[NSString stringWithFormat:@"youtube://watch?v=%@",id]]; // I dont know excatly this one
    NSURL *linkToWeb = [NSURL URLWithString:[NSString stringWithFormat:@"https://www.youtube.com/watch?v=%@",id]]; // this is correct
    
    
    if ([[UIApplication sharedApplication] canOpenURL:linkToApp]) {
        // Can open the youtube app URL so launch the youTube app with this URL
        [[UIApplication sharedApplication] openURL:linkToApp];
    }
    else{
        // Can't open the youtube app URL so launch Safari instead
        [[UIApplication sharedApplication] openURL:linkToWeb];
    }
}

NSString *lastAction = @"index";

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    
    NSURL *URL = [request URL]; //Get the URL
    lastAction = [URL host];
    
    //NSLog(@"Start loading.");
    
    //NSLog(@"navigationType= %d\n\n", (int)navigationType);
    //NSLog(@"scheme= %@ %@\n\n", [URL scheme], SITE_SCHEMA);
    //NSLog(@"host= %@\n\n", [URL host]);
    //NSLog(@"path=%@\n\n", [URL path]);
    NSLog(@"shouldStartLoadWithRequest URL = %@\n\n", [request URL]);
    
    if (navigationType == UIWebViewNavigationTypeLinkClicked
        || navigationType == UIWebViewNavigationTypeOther
        || navigationType == UIWebViewNavigationTypeFormSubmitted)
    {
        NSLog(@"navigationType=%ld", (long)navigationType);
        
        if ( [[URL scheme] isEqualToString:SITE_SCHEMA] ) {
            if ( [[URL host] isEqualToString:@"showAlert"]){
                [self hideProgressDialog];
                NSString *callback = [self getQueryStringValueFromUrl:URL :@"callback"];
                NSString *msg = [self getQueryStringValueFromUrl:URL :@"msg"];
                NSString *type = [self getQueryStringValueFromUrl:URL :@"type"];
                
                if([msg isEqualToString:@"openDownloadPage"]) {
                    msg = @"ALERT! For the best performance and security, you may now please download and install the latest version of PAYYAP  - The Payments App\u2122\n\nThank you!";
                }
                else if([msg isEqualToString:@"InviteToPAYYAPNowSuccessMessage"]) {
                    msg = @"SUCCESS! Your selected associates will be invited to PAYYAP via SMS within the next few hours.(Please check your email for details about the PAYYAP affiliate program.)\n\nThank you for using PAYYAP --The Payments App\u2122";
                }

                
                [self showAlert:type :msg :callback];
                
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"showConfirm"]){
                [self hideProgressDialog];
                //NSString *callback = [self getQueryStringValueFromUrl:URL :@"callback"];
                NSString *msg = [self getQueryStringValueFromUrl:URL :@"msg"];
                NSString *type = [self getQueryStringValueFromUrl:URL :@"type"];
                [self confirm: type : msg];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"confirmRefundThisTransaction"]) {
                [self confirm:@"confirmRefundThisTransaction" : @"You are about to REFUND this transaction. Click OK to complete this refund now. (Or CANCEL this refund to keep the payment.)"];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"confirmAutoCompletePaymentInBackground"]) {
                NSString *msg = [self getQueryStringValueFromUrl:URL :@"msg"];
                [self confirm:@"confirmAutoCompletePaymentInBackground" : msg];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"confirmInviteToPAYYAPNow"]) {
                NSString *msg = [self getQueryStringValueFromUrl:URL :@"msg"];
                [self confirm:@"confirmInviteToPAYYAPNow" : msg];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"confirmAccountVerification"]) {
                [self hideProgressDialog];
                [self confirm:@"ConfirmAccountVerification" : @"Before you begin taking MasterCard / VISA payments using this account, we need for you to simply verify your identity. Please continue to begin the Identity Verification Wizard now."];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"account_access"]) {
                NSString *callback = [self getQueryStringValueFromUrl:URL :@"callback"];
                NSString *emailaddress = [self getQueryStringValueFromUrl:URL :@"emailaddress"];
                if([callback isEqualToString:@"showMemberEmailAddress"]) {
                    emailaddress = [self getUserData: @"emailaddress"];
                }
                else{
                    [self saveUserData:@"emailaddress": emailaddress];
                }
                
                NSString *phoneNumber = [self getUserData:@"phoneNumber"];
                NSString *simSerialNumber = [self getUserData:@"simSerialNumber"];
                NSString *deviceId = [self getUserData:@"deviceId"];
                NSString *deviceType = [self getUserData:@"deviceType"];
                NSString *versionName = [self getUserData:@"versionName"];
                
                NSDictionary * paramsDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:emailaddress, phoneNumber, simSerialNumber, deviceId, deviceType, versionName, nil]
                                                                            forKeys:[NSArray arrayWithObjects:@"emailaddress", @"PAYYAP_device_telephone_number", @"PAYYAP_sim_serial_number", @"PAYYAP_device_id", @"PAYYAP_device_type", @"PAYYAP_version", nil]];

                NSError * err;
                NSData * jsonData = [NSJSONSerialization dataWithJSONObject:paramsDictionary options:0 error:&err];
                NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
                
                NSLog(@"jsonData as string:\n%@", jsonString);
                
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"%@('%@');", callback, jsonString]];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"setMemberHash"]) {
                NSString *member_hash = [self getQueryStringValueFromUrl:URL :@"member_hash"];
                [self saveUserData:@"member_hash": member_hash];            
            }
            else if ( [[URL host] isEqualToString:@"login"]){
                NSString *account_hash = [self getQueryStringValueFromUrl:URL :@"account_hash"];
                //NSString  *path = [URL path];
                //path = [path substringFromIndex:1];
                //NSLog(@"path = %@\n\n", path);
                //NSArray* pathParts = [path componentsSeparatedByString: @":"];
                //NSString* hash = [pathParts objectAtIndex: 0];
                //NSString* remember = [pathParts objectAtIndex: 1];
                //NSLog(@"hash = %@\n\n", hash);
                //NSLog(@"remember = %@\n\n", remember);
                //if([remember isEqualToString:@"true"]) [self saveUserHash:hash];
                //else
                [self saveUserHash:account_hash];
                
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showHome('%@');", account_hash]];
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showHideLoader();"]];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"home"]){
                [self showHomeScreen];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"logout"]){
                [self saveUserHash:@""];
                //[self saveUserData:@"member_hash" : @"" ];
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showLogin();" ]];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"showProgressDialog"]){
                NSString *processingMessage = [self getQueryStringValueFromUrl:URL :@"processingMessage"];
                if([processingMessage isEqualToString:@""]) processingMessage = @"Preparing...";
                [self showProgressDialog:processingMessage];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"hideProgressDialog"]){
                [self hideProgressDialog];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"openLink"]){
                NSString  *path = [URL path];
                path = [path substringFromIndex:1];
                NSString *urlString = [NSString stringWithFormat: @"https://photo.%@/%@", API_DOMAIN, path];
                if([path containsString:@"http"] || [path containsString:@"https://"] ){
                    urlString = path;
                }
                else if([path containsString:@"youtube"]){
                    NSString *vid = [self getQueryStringValueFromUrl:URL :@"vid"];
                    [self watchYoutTubeVideo:vid];
                    return NO;
                }
                NSURL *url = [NSURL URLWithString:urlString];
                [[UIApplication sharedApplication] openURL:url];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"takePhoto"]){
                mediaAction = @"takePhoto";
                if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    
                    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                          message:@"Device has no camera"
                                                                         delegate:nil
                                                                cancelButtonTitle:@"OK"
                                                                otherButtonTitles: nil];
                    
                    [myAlertView show];
                    
                }
                else{
                    imageNo = [[self getQueryStringValueFromUrl:URL :@"imageNo"] intValue];
                    
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = self;
                    picker.allowsEditing = YES;
                    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    
                    [self presentViewController:picker animated:YES completion:NULL];
                }
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"selectPhoto"]){
                mediaAction = @"selectPhoto";
                imageNo = [[self getQueryStringValueFromUrl:URL :@"imageNo"] intValue];
                
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = self;
                picker.allowsEditing = YES;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                
                [self presentViewController:picker animated:YES completion:NULL];
                
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"showSelectedImage"]){
                [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showSelectedImage('%@', '%d');", filePath, imageNo ]];
                
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"openConfirmModal"]){
                if([mediaAction isEqualToString:@"selectPhoto"]){
                    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"startUploading('%d');", imageNo]];
                }
                else{
                    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                             delegate:self
                                                                    cancelButtonTitle:@"Delete?"
                                                               destructiveButtonTitle:nil
                                                                    otherButtonTitles:@"Keep Photo?", nil];
                    [actionSheet showInView: webView ];
                }
            }
            else if ( [[URL host] isEqualToString:@"uploadPhoto"]){
                [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
                transaction_session_hash = [self getQueryStringValueFromUrl:URL :@"transaction_session_hash"];
                //[self uploadPhotoInBackground];
                [self uploadPhoto];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"startUpdatingPhoto"]){
                [self showProgressDialog: @"Updating..."];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"confirmInviteToPAYYAPNow"]){
                [self confirm:@"confirmInviteToPAYYAPNow":@"Earn money by talking about PAYYAP!\n\nWe pay you 25% of net processing revenue from all referrals - for life -- directly into your PAYYAP or bank account!\n\nStart earning money today: Tell (up to 20) of your friends about PAYYAP now... :)"];
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"openContact"]){
                NSString  *path = [URL path];
                path = [path substringFromIndex:1];
                //NSLog(@"path = %@\n\n", path);
                if ( [path isEqualToString:@"tell_friends_form"]){
                    //[self showProgressDialog:@"Processing..."];
                    [self openContactsWidthAddressBook:@"upload"];
                    //[self uploadContactsInBackground];
                   
                    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"fillContactsCallLogsForm('%@');", [self openContactsWidthAddressBook:@"form"] ]];
                }
                else{
                    [self openContactPicker];
                }
                
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"actionBarItem"]){
                NSString  *action = [self getQueryStringValueFromUrl:URL :@"action"];
                
                if( [action isEqualToString:@"menu_payyap_send_to_background"]){
                    //home button press programmatically
                    UIApplication *app = [UIApplication sharedApplication];
                    [app performSelector:@selector(suspend)];
                    
                    //wait 2 seconds while app is going background
                    //[NSThread sleepForTimeInterval:2.0];
                    
                    //exit app when app is in background
                    //exit(0);
                }
                else if( [action isEqualToString:@"menu_payyap_turn_off"]){
                    //exit app when app is in background
                    //exit(0);
                    
                    //home button press programmatically
                    UIApplication *app = [UIApplication sharedApplication];
                    [app performSelector:@selector(suspend)];
                    
                    //wait 2 seconds while app is going background
                    [NSThread sleepForTimeInterval:2.0];
                    
                    //exit app when app is in background
                    exit(0);
                }
                else if( [action isEqualToString:@"menu_payyap_log_off"]){
                    //
                    [self saveUserHash:@""];
                    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showLogin();" ]];
                }
                else if( [action isEqualToString:@"menu_payyap_help"]){
                    //
                    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: @"https://support.payyap.network/?from_payyap_app=true"]];
                }
                else if( [action isEqualToString:@"registerEIN"]){
                    //
                    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: @"https://support.payyap.network/FAQ_EIN.nsdb"]];
                }
                else if( [action isEqualToString:@"force_update"]){
                    //
                    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: @"https://support.payyap.network/FAQ_force_update.nsdb"]];
                }
                return NO;
            }
            else if ( [[URL host] isEqualToString:@"verification_region"]){
                NSString  *path = [URL path];
                path = [path substringFromIndex:1];
                //NSLog(@"path = %@\n\n", path);
                
                [self saveUserData:@"verification_region": path];
                
                return NO;
            }
            else{
                NSLog(@"NO Action");
                return NO;
            }
        }
        else if ( [[URL scheme] isEqualToString:@"http"] || [[URL scheme] isEqualToString:@"https"]) {
            [[UIApplication sharedApplication] openURL:URL];
            return NO;
        }
        else if([[URL absoluteString] containsString:@"mailto:" ]){
            NSLog(@"mailto URL= %@", [URL absoluteString]);
            
            //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[URL absoluteString]]];
            [[UIApplication sharedApplication] openURL:URL];
            return NO;
        }
    }
    
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"Last Action = %@",lastAction);
    NSString *userHash = [self getUserHash];
    NSLog(@"userHash= %@\n\n", userHash);
    
    if(userHash==(id) [NSNull null] || [userHash length]==0 || [userHash isEqualToString:@""]){
        //LOGIN
        //html = [self replaceLoginHomePageTemplateVariable : html : @"" : @"display:none;" ];
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showLogin();" ]];
    }
    else {
        //HOME
        //html = [self replaceLoginHomePageTemplateVariable : html : @"display:none;" : @"" ];
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"showHome('%@');", [self getUserHash]]];
    }
    
}

- (NSString*)openContactsWidthAddressBook:(NSString*)type{
    ABAddressBookRef addressBook = ABAddressBookCreate();
    
    
    __block BOOL accessGranted = NO;
    
    if (&ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
            accessGranted = granted;
            dispatch_semaphore_signal(semaphore);
        });
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        //dispatch_release(semaphore);
    }
    
    else { // We are on iOS 5 or Older
        accessGranted = YES;
        //[self getContactsWithAddressBook:addressBook];
    }
    
    if (accessGranted) {
        return [self getContactsWithAddressBook:addressBook:type];
    }
    return @"{}";
}

// Get the contacts.
- (NSString *)getContactsWithAddressBook:(ABAddressBookRef )addressBook :(NSString*)type{
    
    NSMutableArray *contacts = [[NSMutableArray alloc] init];
    NSMutableArray *contactList = [[NSMutableArray alloc] init];
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
    
    NSMutableDictionary *contactsCallLogs=[NSMutableDictionary dictionary];
    
    for (int i=0;i < nPeople;i++) {
        NSMutableDictionary *dOfPerson=[NSMutableDictionary dictionary];
        
        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
        
        //For username and surname
        ABMultiValueRef phones =(__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonPhoneProperty));
        
        CFStringRef firstName, middleName, lastName;
        firstName = ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        middleName = ABRecordCopyValue(ref, kABPersonMiddleNameProperty);
        lastName  = ABRecordCopyValue(ref, kABPersonLastNameProperty);
        
        if(firstName == NULL || firstName == nil) firstName = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);
        if(middleName == NULL || middleName == nil) middleName = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);
        if(lastName == NULL || lastName == nil) lastName = CFStringCreateWithCString (NULL, "", kCFStringEncodingUTF8);
        
        [dOfPerson setObject:[NSString stringWithFormat:@"%@", firstName] forKey:@"firstName"];
        [dOfPerson setObject:[NSString stringWithFormat:@"%@", middleName] forKey:@"middleName"];
        [dOfPerson setObject:[NSString stringWithFormat:@"%@", lastName] forKey:@"lastName"];
        
        //For Email ids
        ABMutableMultiValueRef eMail  = ABRecordCopyValue(ref, kABPersonEmailProperty);
        if(ABMultiValueGetCount(eMail) > 0) {
            [dOfPerson setObject:(__bridge NSString *)ABMultiValueCopyValueAtIndex(eMail, 0) forKey:@"email"];
            
        }
        
        //For Phone number
        NSString* mobileLabel;
        
        for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
            mobileLabel = (__bridge NSString*)ABMultiValueCopyLabelAtIndex(phones, j);
            if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:@"phone"];
            }
            else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
            {
                [dOfPerson setObject:(__bridge NSString*)ABMultiValueCopyValueAtIndex(phones, j) forKey:@"phone"];
                break ;
            }
            
        }
        if([dOfPerson valueForKey:@"phone"] != NULL){
            [contactList addObject:dOfPerson];
        }
        
        if([type isEqualToString:@"form"] && i > 20) break;
        
    }
    [contactsCallLogs setObject:contactList forKey:@"callLogs"];
    [contactsCallLogs setObject:contacts forKey:@"contacts"];
    //NSLog(@"Contacts = %@",contactsCallLogs);
    
    NSError * err;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:contactsCallLogs options:0 error:&err];
    if([type isEqualToString:@"upload"]) jsonData = [NSJSONSerialization dataWithJSONObject:contactList options:0 error:&err];
    NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonData as string:\n%@", jsonString);
    
    if([type isEqualToString:@"form"]) return jsonString;
    else if([type isEqualToString:@"upload"]) [self uploadContacts:jsonString];
    return @"{}";
}

- (void)openContactPicker{
    
    if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusDenied ||
        ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusRestricted){
        //1
        NSLog(@"Denied");
    } else if (ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusAuthorized){
        //2
        NSLog(@"Authorized");
        [self selectContact];
    } else{ //ABAddressBookGetAuthorizationStatus() == kABAuthorizationStatusNotDetermined
        //3
        NSLog(@"Not determined");
        
        ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, nil), ^(bool granted, CFErrorRef error) {
            if (!granted){
                //4
                NSLog(@"Just denied");
                return;
            }
            //5
            NSLog(@"Just authorized");
            [self selectContact];
        });
    }
}

- (void)selectContact{
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];

    picker.peoplePickerDelegate = self;


    //[self presentModalViewController:picker animated:YES];

    [self presentViewController:picker animated:YES completion:nil];
}

- (void)peoplePickerNavigationControllerDidCancel:

(ABPeoplePickerNavigationController *)peoplePicker {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person {
    [self displayPerson:person];
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
                         didSelectPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier
{
    
}


- (void)displayPerson:(ABRecordRef)person{
    
    NSString *firstName;
    NSString *middleName;
    NSString *lastName;
    NSString *retrievedName;
    // get the first name
    firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    //get the middle name
    middleName = (__bridge_transfer NSString*)ABRecordCopyValue(person, kABPersonMiddleNameProperty);
    // get the last name
    lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    
    //set the name
    if (firstName != NULL && middleName != NULL && lastName != NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@ %@ %@",firstName,middleName,lastName];
    }
    
    if (firstName != NULL && middleName != NULL & lastName == NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@ %@",firstName, middleName];
    }
    
    if (firstName != NULL && middleName == NULL && lastName != NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@ %@",firstName,lastName];
    }
    
    if (firstName != NULL && middleName == NULL && lastName == NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@",firstName];
    }
    
    if (firstName == NULL && middleName != NULL && lastName != NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@ %@",middleName, lastName];
    }
    
    if (firstName == NULL && middleName != NULL && lastName == NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@",middleName];
    }
    
    if (firstName == NULL && middleName == NULL && lastName != NULL)
    {
        retrievedName = [[NSString alloc] initWithFormat:@"%@", lastName];
    }
    
    
    ABMultiValueRef emailAddress = ABRecordCopyValue(person, kABPersonEmailProperty);
    NSString *email = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emailAddress, 0);
    if(email==NULL) email = @"";
    NSLog(@"email: %@", email);
    
    NSString* phone = nil;
    
    ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty);
    
    if (ABMultiValueGetCount(phoneNumbers) > 0) {
        phone = (__bridge_transfer NSString*)
        ABMultiValueCopyValueAtIndex(phoneNumbers, 0);
    } else {
        phone = @"";
    }
    
    CFRelease(phoneNumbers);
    
    NSLog(@"displayPerson name = %@, email = %@, phone = %@\n\n", retrievedName, email, phone);
    
    [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"fillFormDataFromContact('%@', '%@', '%@');", email, retrievedName, phone ]];
    
}



- (void)uploadContactsInBackground
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Do background work
        //NSString *response = [self uploadPhoto];
        
        [self openContactsWidthAddressBook:@"upload"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //Update UI
            [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
            
            //[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadFinished('%@');", [response stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]]];
            
        });
    });
    
}
- (void)uploadPhotoInBackground
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Do background work
        NSString *response = [self uploadPhoto];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //Update UI
            [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
            
            [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadFinished('%@');", [response stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]]];
            
        });
    });
    
}

NSString *uploadFor = @"";
long selectedItemIndex = -1;
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"The %@ button was tapped at index %ld.", [actionSheet buttonTitleAtIndex:buttonIndex], (long)buttonIndex);
    selectedItemIndex = -1;
    if( [[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Keep Photo?"] ){
        //KEEP
        uploadFor = [actionSheet buttonTitleAtIndex:buttonIndex];
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"startUploading('%d');", imageNo]];
    }
    //else if( [[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Delete?"] || [[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:@"Cancel"] ){
    else{
        //DELETE
        NSLog(@"REMOVE");
        
        [self removeSelectedImage:imageNo];
        
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"deleteSelectedImage('%d');", imageNo]];
    }
}

- (void)removeSelectedImage:(int) tmpImageNo
{
    NSString *tmpFilename = [[NSString alloc] initWithFormat:@"%d", tmpImageNo];
    tmpFilename = [tmpFilename stringByAppendingString:PHOTO_NAME];
    NSFileManager *manager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSString *documentsDirectory = BASE_PATH ;//[paths objectAtIndex:0];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:tmpFilename];
    NSLog(@"PHOTO PATH %@", savedImagePath);
    [manager removeItemAtPath: savedImagePath error:&error];
}



- (void)showHomeScreen
{
    [self.webView loadHTMLString:[self getHtmlFromTemplate:@"index"]  baseURL:[self baseUrl]];
}

- (void)showLoginScreen
{
    [self.webView loadHTMLString:[self getHtmlFromTemplate:@"index"]  baseURL:[self baseUrl]];
}


-(NSArray*)applicationDocuments {
    return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
}

-(NSString*)applicationDocumentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

NSMutableData *responseData;
-(NSString*)uploadPhoto {
    //int imageNo = 1;
    //NSString *filename = @"";
    //NSString *filePath = @"";
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
    //NSString *path = [NSString stringWithFormat:@"%@/%@", BASE_PATH, filename];
    NSLog(@"Path String= %@",filePath);
    
    NSData *file1Data = [[NSData alloc] initWithContentsOfFile:filePath];
    
    NSString *urlString = [NSString stringWithFormat: @"https://gateway.%@/QUALIFY_Wizard.gate?imageNo=%d", API_DOMAIN, imageNo];
    if (imageNo >= 91 && imageNo <= 96) {
        urlString = [NSString stringWithFormat: @"https://gateway.%@/enable_high_security_chargeback_protection_uploads.gate?imageNo=%d", API_DOMAIN, imageNo];
    }
    NSLog(@"urlString= %@",urlString);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[[NSString stringWithString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", filename]] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:file1Data]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    //device
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"device\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"ios" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //imageNo
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"imageNo\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[[NSString alloc] initWithFormat:@"%d", imageNo] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //action
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"action\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"upload" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    if (imageNo >= 91 && imageNo <= 96) {
        NSLog(@"transaction_session_hash= %@",transaction_session_hash);
        //transaction_session_hash
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Disposition: form-data; name=\"transaction_session_hash\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[transaction_session_hash dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    //uploader_name
    if (imageNo ==1 ) uploadFor = @"account_identity_manager_photo_id_filename";
    else if (imageNo == 2) uploadFor = @"proof_of_business_1_filename";
    else if (imageNo == 3) uploadFor = @"proof_of_business_2_filename";
    else if (imageNo == 4) uploadFor = @"account_identity_manager_business_certificate_filename";
    else if (imageNo == 5) uploadFor = @"account_identity_manager_proof_of_business_location_filename";
    else if (imageNo == 61) uploadFor = @"proof_of_business_3_filename";
    else if (imageNo == 62) uploadFor = @"proof_of_business_4_filename";
    else if (imageNo == 63) uploadFor = @"proof_of_business_5_filename";
    else if (imageNo == 64) uploadFor = @"proof_of_business_6_filename";
    else if (imageNo == 65) uploadFor = @"proof_of_business_7_filename";
    else if (imageNo == 91) uploadFor = @"enable_high_security_chargeback_protection_upload_1_CARD_FRONT";
    else if (imageNo == 92) uploadFor = @"enable_high_security_chargeback_protection_upload_2_CARD_BACK";
    else if (imageNo == 93) uploadFor = @"enable_high_security_chargeback_protection_upload_3_ID_FRONT";
    else if (imageNo == 94) uploadFor = @"enable_high_security_chargeback_protection_upload_4_ID_BACK";
    else if (imageNo == 95) uploadFor = @"enable_high_security_chargeback_protection_upload_5_CUSTOMER";
    else if (imageNo == 96) uploadFor = @"enable_high_security_chargeback_protection_upload_6_RECEIPT";

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"uploader_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[uploadFor dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //hash
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"hash\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[self getUserHash] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //member_hash
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"member_hash\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[self getUserData:@"member_hash"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    //NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    //    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
    //                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    //                               NSLog(@"Finished with status code: %ld", (long)[(NSHTTPURLResponse *)response statusCode ]);
    //
    //                           }];
    
    //NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    //NSLog(@"Return String= %@",returnString);
    
    return @"";
}

-(NSString*)uploadContacts: (NSString *)contacts {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
    //NSString *path = [NSString stringWithFormat:@"%@/%@", BASE_PATH, filename];
    NSLog(@"Path String= %@",filePath);
    
    //NSData *file1Data = [[NSData alloc] initWithContentsOfFile:filePath];
    
    NSString *urlString = [NSString stringWithFormat: @"https://gateway.%@/payyap_member_referral.gate", API_DOMAIN];
    NSLog(@"urlString= %@",urlString);
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    //device
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"contacts\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[contacts dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    
    //hash
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"hash\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[self getUserHash] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    //member_hash
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"member_hash\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[self getUserData:@"member_hash"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
//    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request
//                                                                  delegate:self
//                                                          startImmediately:NO];
//    [connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
//                          forMode:NSRunLoopCommonModes];
//    [connection start];
    
    //NSLog(@"Request Sent");
    
    return @"";
}

- (void)connection:(NSURLConnection *)connection
   didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite    {
    NSLog(@"didSendBodyData %@", connection);
    //NSURLRequest* request = [connection currentRequest];
    NSURL *url = [[connection currentRequest] URL];
    NSString *filename = [url lastPathComponent];
    NSLog(@"filename %@", filename);
    if([filename isEqualToString:@"payyap_member_referral.gate"]){
        
    }
    else{
        int imageNo = [[self getQueryStringValueFromUrl:url :@"imageNo"] intValue];
        
        NSLog(@"Current imageNo: %d",imageNo);
        
        float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
        float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
        int progress_percent = (int)(progress/total* 100);
        NSLog(@"progress/total %f",progress/total);
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"setProgress('%d','%d');", progress_percent, imageNo]];
    }
}

//Delegate methods
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Did Receive Response %@", response);
    responseData = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"Did Receive Data %@", data);
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"Did Fail");
    
    NSURL *url = [[connection currentRequest] URL];
    NSString *filename = [url lastPathComponent];
    NSLog(@"filename %@", filename);
    if([filename isEqualToString:@"QUALIFY_Wizard.gate"] || [filename isEqualToString:@"enable_high_security_chargeback_protection_uploads.gate"]){
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadFinished('{msg:\'Failed\', imageNo:%d}');", imageNo]];
    }
    
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
    NSLog(@"Did Finish");
    // Do something with responseData
    NSString *returnString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Return String= %@",returnString);
    
    NSURL *url = [[connection currentRequest] URL];
    NSString *filename = [url lastPathComponent];
    NSLog(@"filename %@", filename);
    if([filename isEqualToString:@"payyap_member_referral.gate"]){
        [self hideProgressDialog];
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"contactUploadFinished();"]];
    }
    else if([filename isEqualToString:@"QUALIFY_Wizard.gate"] || [filename isEqualToString:@"enable_high_security_chargeback_protection_uploads.gate"]){
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"uploadFinished('%@');", [returnString stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]]];
    }
}


- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
                               if ( !error )
                               {
                                   //NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

NSDictionary *photoBANGK_data = nil;
- (void)sendHttpGetAsync: (NSString*) urlString{
    NSURL *url = [NSURL URLWithString:urlString];
    NSLog(@"Request URL: %@", url);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%s - %d # responseStr = %@", __PRETTY_FUNCTION__, __LINE__, responseStr);
        
        
        [self hideProgressDialog];
        
        NSError *error;
        photoBANGK_data = [NSJSONSerialization
                           JSONObjectWithData:data
                           options:kNilOptions
                           error:&error];
        
        
        if( error )
        {
            NSLog(@"%@", [error localizedDescription]);
            photoBANGK_data = nil;
        }
        else {
            NSLog(@"photoBANGK_data=%@", photoBANGK_data);
            
            if([photoBANGK_data objectForKey:@"msg"] ){
                NSString* msg = [photoBANGK_data valueForKey:@"msg"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showAlert:msg];
                });
            }
            else{
                
            }
        }
        
        
    }];
}

- (NSString *) getDocumentPath{
    
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    
    return documentsDirectory;
}

- (NSString *) getApplicationPath{
    return [[NSBundle mainBundle] bundlePath];
}

- (NSString *)baseUrlString{
    return [[self getApplicationPath] stringByAppendingPathComponent: @"index.html"];
}

- (NSURL *)baseUrl{
    return [NSURL fileURLWithPath:[self baseUrlString]];
}


- (NSString *)getHtmlFromTemplate:(NSString *)templateFile{
    NSString *dir = @"";
    
    NSString* fn = [BASE_PATH stringByAppendingPathComponent:[dir stringByAppendingPathComponent:[templateFile stringByAppendingString:@".html"]]];
    
    NSError *error;
    NSString* template = [NSString stringWithContentsOfFile:fn encoding:NSASCIIStringEncoding error:&error];
    if([templateFile isEqualToString:@"index"]){
        template = [self replaceSiteSchemaTemplateVariable: template];
    }
    
    return template;
}


- (NSString *)replaceSiteSchemaTemplateVariable:(NSString *)templateHTML{
    
    //NSLog(@"HTML BEFORE %@", templateHTML);
    NSString *verification_region = [self getUserData:@"verification_region"];
    if(verification_region == nil) verification_region = @"united_states";
    NSString *verification_form = [self getHtmlFromTemplate:@"verfication_form"];
    NSString *verification_photo_id_form = [self getHtmlFromTemplate:@"verification_form_advanced"];
    NSString *calling_code_dropdown = [self getHtmlFromTemplate:@"calling_code_dropdown"];
    
    NSString *emailaddress = [self getUserData:@"emailaddress"];
    NSString *member_hash = [self getUserData:@"member_hash"];
    
    NSString *PAYYAP_version = [self getUserData:@"versionName"];
    NSString *PAYYAP_device_type = [self getUserData:@"deviceType"];
    
    NSString *PAYYAP_device_id = [self getUserData:@"deviceId"];
    NSString *PAYYAP_device_telephone_number = [self getUserData:@"phoneNumber"];
    NSString *PAYYAP_sim_serial_number = [self getUserData:@"simSerialNumber"];
    
    NSArray *templateVariables = [NSArray arrayWithObjects:@"[[startPage]]", @"[[SITE_SCHEMA]]", @"[[SITE_TITLE]]", @"[[API_DOMAIN]]", @"[[VERIFICATION_FORM]]", @"[[VERIFICATION_PHOTO_ID_FORM]]", @"[[VERIFICATION_REGION]]", @"[[EMAIL_ADDRESS]]", @"[[MEMBER_HASH]]", @"[[PAYYAP_version]]", @"[[PAYYAP_device_type]]", @"[[PAYYAP_device_id]]", @"[[PAYYAP_device_telephone_number]]", @"[[PAYYAP_sim_serial_number]]", @"[[CALLING_CODE_DROPDOWN]]", nil];
    NSArray *replacementValues = [NSArray arrayWithObjects: startPage, SITE_SCHEMA, SITE_TITLE, API_DOMAIN, verification_form, verification_photo_id_form, verification_region, emailaddress, member_hash, PAYYAP_version, PAYYAP_device_type, PAYYAP_device_id, PAYYAP_device_telephone_number, PAYYAP_sim_serial_number, calling_code_dropdown, nil];
    NSMutableDictionary *replaceDicValues = [NSMutableDictionary dictionaryWithObjects:replacementValues forKeys:templateVariables];
    NSString *pageHtml = [self replaceTemplateVariable:templateHTML :replaceDicValues];
    //NSLog(@"HTML AFTER %@", pageHtml);
    return pageHtml;
}

- (NSString *)replaceLoginHomePageTemplateVariable: (NSString *)templateHTML : (NSString *)loginPage : (NSString *)homePage{
    //NSLog(@"HTML BEFORE %@", templateHTML);
    NSArray *templateVariables = [NSArray arrayWithObjects:@"[[LOGIN_PAGE]]", @"[[HOME_PAGE]]", nil];
    NSArray *replacementValues = [NSArray arrayWithObjects:loginPage, homePage, nil];
    NSMutableDictionary *replaceDicValues = [NSMutableDictionary dictionaryWithObjects:replacementValues forKeys:templateVariables];
    NSString *pageHtml = [self replaceTemplateVariable:templateHTML :replaceDicValues];
    //NSLog(@"HTML AFTER %@", pageHtml);
    return pageHtml;
}

- (NSString *)replaceTemplateVariable:(NSString *)templateHTML :(NSMutableDictionary *)replament{
    
    NSString *finalHTML = templateHTML;
    
    for (id key in replament) {
        id value = [replament objectForKey: key];
        finalHTML = [finalHTML stringByReplacingOccurrencesOfString:key withString:value];
    }
    
    return finalHTML;
}

- (NSString *)buildURL:(NSString *)url{
    NSString *urlString = [NSString stringWithFormat: @"%@/%@", API_HOST, url];
    return urlString;
}

- (NSMutableDictionary *) getFormDataByFormId:(NSString *)formId{
    NSString *formIdJS = @"";
    formIdJS = [formIdJS stringByAppendingFormat:@"getFormDataSerialized('#%@')", formId];
    NSString *formData = [self.webView stringByEvaluatingJavaScriptFromString:formIdJS];
    NSMutableDictionary* queryDict = [NSMutableDictionary dictionary];
    //NSLog(@"getFormDataByFormId = %@\n\n", formData);
    queryDict = [self formDataToDictionary:formData];
    //NSLog(@"getFormDataByFormId = %@\n\n", queryDict);
    return  queryDict;
}

- (NSMutableDictionary *)formDataToDictionary:(NSString *)formData {
    NSArray* queryArray = [formData componentsSeparatedByString:@"&"];
    NSMutableDictionary* queryDict = [NSMutableDictionary dictionary];
    for (NSString* query in queryArray) {
        NSUInteger indexOfEqualsSign = [query rangeOfString:@"="].location;
        if (indexOfEqualsSign != NSNotFound) {
            NSString* key = [[query substringToIndex:indexOfEqualsSign] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
            NSString* value = [[query substringFromIndex:indexOfEqualsSign+1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
            [queryDict setValue:value forKey:key];
        }
    }
    return queryDict;
}

@end
