//
//  VFYIDSuccessWrapper.m
//  Verif-y
//
//  Created by MTN on 05/09/20.
//

#import "VFYIDSuccessWrapper.h"
#import "VFYIDSelfieGuideWrapper.h"
#import "Utilities.h"
#import "VFYConstant.h"
#import "VFYButton.h"
#import "VFYSuggestionPopup.h"

#import "VFYAuditManager.h"

@interface VFYIDSuccessWrapper ()
/** IBoutlet for labels */
@property (weak, nonatomic) IBOutlet UILabel *LbFName;
@property (weak, nonatomic) IBOutlet UILabel *LbLName;
@property (weak, nonatomic) IBOutlet UILabel *LbGender;
@property (weak, nonatomic) IBOutlet UILabel *LbDNumber;
@property (weak, nonatomic) IBOutlet UILabel *LbDType;
@property (weak, nonatomic) IBOutlet UILabel *LbDOB;
@property (weak, nonatomic) IBOutlet UILabel *LbDOE;
@property (weak, nonatomic) IBOutlet UILabel *LbNation;
@property (weak, nonatomic) IBOutlet UILabel *LbADS;
@property (weak, nonatomic) IBOutlet UILabel *LbFullName;
@property (weak, nonatomic) IBOutlet UILabel *LbDsc;
@property (weak, nonatomic) IBOutlet UILabel *LbIssuer;
/** IBoutlet for error labels */
@property (weak, nonatomic) IBOutlet UILabel *LbERFName;
@property (weak, nonatomic) IBOutlet UILabel *LbERLName;
@property (weak, nonatomic) IBOutlet UILabel *LbERGender;
@property (weak, nonatomic) IBOutlet UILabel *LbERDNumber;
@property (weak, nonatomic) IBOutlet UILabel *LbERDType;
@property (weak, nonatomic) IBOutlet UILabel *LbERDOB;
@property (weak, nonatomic) IBOutlet UILabel *LbERDOE;
@property (weak, nonatomic) IBOutlet UILabel *LbERNation;
@property (weak, nonatomic) IBOutlet UILabel *LbERADS;
@property (weak, nonatomic) IBOutlet UILabel *LbERIssuer;
/** IBoutlet for UIImageviews */
@property (weak, nonatomic) IBOutlet UIImageView *faceImage;
@property (weak, nonatomic) IBOutlet UIImageView *frontSide;
@property (weak, nonatomic) IBOutlet UIImageView *backSide;
@property (weak, nonatomic) IBOutlet UIScrollView *BodyScrollView;
/** IBoutlet for UITextView */
@property (weak, nonatomic) IBOutlet UITextView *TvADS;
/** IBoutlet for all UITextfields */
@property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *fields;
/** IBoutlet for UIButton */
@property (weak, nonatomic) IBOutlet VFYButton *BtContinue;
@property (nonatomic, strong) NSMutableArray *failedValidateCount;
/** Variable related to picker */
@property (nonatomic, strong) UIDatePicker *DOBPickerView;
@property (nonatomic, strong) UIDatePicker *DOEPickerView;
@property (nonatomic, strong) UIPickerView *natlPickerView;
@property (nonatomic, strong) UIPickerView *genderPickerView;
@property (nonatomic, strong) NSArray *countryNames;
@property (nonatomic, strong) NSArray *genders;
//@property (nonatomic, strong) NSArray *documentType;
@property (strong, nonatomic) UIColor *fontColor;
@property (strong, nonatomic) UIColor *headerColor;
@property (strong, nonatomic) UIColor *backgroundColor;
@property (strong, nonatomic) UIColor *headerFontColor;
/** IBoutlet for extra varibles */
@property (weak, nonatomic) IBOutlet UITextField *TfDOB;
@property (weak, nonatomic) IBOutlet UITextField *TfDOE;
@property (weak, nonatomic) IBOutlet UITextField *TfCountry;
@property (weak, nonatomic) IBOutlet UITextField *TfGender;
@property (weak, nonatomic) IBOutlet UITextField *activeField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) VFYIDSuccess *idSuccess;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYIDSuccessWrapper

@synthesize LbFName, LbLName, LbGender, LbDNumber, LbDType, LbDOB, LbDOE, LbNation, LbADS;
@synthesize sharedInstance;
@synthesize callDirectlyFlag;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (@available(iOS 13.0, *)) {
         self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    self.failedValidateCount = [NSMutableArray new];
    self.TvADS.delegate = (id)self;
    self.idSuccess = [[VFYIDSuccess alloc] init];
    //[self.view setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    [self.BodyScrollView setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    self.sharedInstance = [VFYVerifyApp sharedInstance];
    /** observer is use to receive values from Nth child to current view */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(idSuccessCallFromNthChild:) name:VFY_OBSERVER_IDSUCCESS object:nil];
    self.fontColor = [Utilities colorFromColorString:self.sharedInstance.bodyTextColor];
    self.headerColor = [Utilities colorFromColorString:self.sharedInstance.headerColor];
    self.backgroundColor = [Utilities colorFromColorString:self.sharedInstance.bodyColor];
    self.headerFontColor = [Utilities colorFromColorString:self.sharedInstance.headerTextColor];
    [self setLocalizationText];
    [self setBrandingColor];
    //[self setCloseButton];
    [self addDOBPickerView];
    [self addDOEPickerView];
    [self addNationalityPickerView];
    [self addGenderPickerView];
    [self setCountry];
    [self setGender];
    [self setValues];
    [self registerForKeyboardNotifications];
    [self setLabelAlignment];
    //[self.TvADS setTextContainerInset:UIEdgeInsetsZero];
    //Remove the padding from the uitextview(address field)
    self.TvADS.textContainer.lineFragmentPadding = 0;
}

/** Receive method use to handle call from nth child */
- (void) idSuccessCallFromNthChild:(NSNotification *)notify {
    NSLog(@"dataReceived :%@", notify.object);
    VFYIDSuccess *vfySuccess = (VFYIDSuccess*)notify.object;
    [self.idGuide callClose:IDSuccessComplete PassValue:vfySuccess];
}

/**
  Add color to branding and corner button
*/
- (void) setBrandingColor {
    /* Set button style */
    [self.BtContinue animateOnPress:FALSE borderColor:[Utilities colorFromColorString:[self.sharedInstance buttonBorderColor]] backGroundColor:[Utilities colorFromColorString:[self.sharedInstance buttonBackgroundColor]] textColor:[Utilities colorFromColorString:[self.sharedInstance buttonTextColor]]];
    /* Set rounded corner style to image */
    self.faceImage.layer.cornerRadius = 10;
    self.faceImage.clipsToBounds = true;
    
    self.frontSide.layer.cornerRadius = 10;
    self.frontSide.clipsToBounds = true;
    self.frontSide.layer.borderWidth = 1.0;
    self.frontSide.layer.borderColor = [[UIColor grayColor] CGColor];
    
    self.backSide.layer.cornerRadius = 10;
    self.backSide.clipsToBounds = true;
    self.backSide.layer.borderWidth = 1.0;
    self.backSide.layer.borderColor = [[UIColor grayColor] CGColor];
        
    [self CustomTitle];
}

/** Set border on rotation of device */
- (void) viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    for (UITextField* field in self.fields) {
        field.delegate = (id)self;
        //[self setBorder:field];
    }
}

 -(void)viewWillAppear:(BOOL)animated {
  //[self.idGuide callClose:IDFailedGuideWrapper];
  [super viewWillAppear:animated];
}

/** Set the extracted values to page */
- (void) setValues {
    
    MBBlinkIdCombinedRecognizer *mbCombine = self.recognizerCollection;
    NSString *strMessage = [NSString string];
    /*for (NSUInteger i = 0; i < self.recognizerCollection.recognizerList.count; ++i) {
        if([[self.recognizerCollection.recognizerList objectAtIndex:i] isKindOfClass:[MBBlinkIdCombinedRecognizer class]]){
            mbCombine = (MBBlinkIdCombinedRecognizer*)[self.recognizerCollection.recognizerList objectAtIndex:i];
            self.idSuccess.isSuccessful = true;
        }
    } */
    self.idSuccess.isSuccessful = true;
    //mbCombine.result.classInfo.type
    /*if(mbCombine.result.fullName != nil) {
        self.LbFullName.text = mbCombine.result.fullName;
        self.idSuccess.fullName = self.LbFullName.text;
    } */
    if(mbCombine.result.address != nil) {
        self.TvADS.text = mbCombine.result.address;
        self.idSuccess.extractedAddress = self.TvADS.text;
    }
    if(mbCombine.result.faceImage.image != nil) {
        self.faceImage.image = mbCombine.result.faceImage.image;
        self.idSuccess.faceImage = [Utilities compressPNGBase64:self.faceImage.image];
    }
    if(mbCombine.result.fullDocumentFrontImage.image != nil) {
        self.frontSide.image = mbCombine.result.fullDocumentFrontImage.image;
        self.idSuccess.documentFrontImage = [Utilities compressPNGBase64:self.frontSide.image];
    } else {
           self.frontSide.hidden = true;
    }
    if(mbCombine.result.fullDocumentBackImage.image != nil) {
        self.backSide.image = mbCombine.result.fullDocumentBackImage.image;
        self.idSuccess.documentBackImage = [Utilities compressPNGBase64:self.backSide.image];
    } else {
        self.backSide.hidden = true;
    }
    
    //mbCombine.result.faceImage;
    for (UITextField* field in self.fields) {
        switch (field.tag) {
            case FirstName:
                {
                    NSString *firstName = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.secondaryID length] == 0) ? mbCombine.result.firstName : mbCombine.result.mrzResult.secondaryID : mbCombine.result.firstName;
                    field.text = [firstName capitalizedString];
                    self.idSuccess.extractedFirstName = field.text;
                    break;
                }
            case LastName:
                {
                    NSString *lastName = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.primaryID length] == 0) ? mbCombine.result.lastName : mbCombine.result.mrzResult.primaryID : mbCombine.result.lastName;
                    field.text = [lastName capitalizedString];
                    self.idSuccess.extractedLastName = field.text;
                    break;
                }
            case Gender:
                {
                    NSString *gender = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.gender length] == 0) ? mbCombine.result.sex : mbCombine.result.mrzResult.gender : mbCombine.result.sex;
                    if([gender length]>0 && [@"f" caseInsensitiveCompare:gender] == NSOrderedSame) {
                        gender = @"female";
                    } else if([gender length]>0 && [@"m" caseInsensitiveCompare:gender] == NSOrderedSame) {
                        gender = @"male";
                    }
                    field.text = [gender capitalizedString];
                    self.idSuccess.extractedGender = field.text;
                    break;
                }
            case DocumentNumber:
                {
                    NSString *docNumber = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.documentNumber length] == 0) ? mbCombine.result.documentNumber : mbCombine.result.mrzResult.documentNumber : mbCombine.result.documentNumber;
                    field.text = [docNumber stringByReplacingOccurrencesOfString:@"<" withString:@""];
                    self.idSuccess.extractedIdDocumentNumber = field.text;
                    break;
                }
            case DocumentType:
                {
                    field.text = [self getDocumentType:mbCombine];
                    self.idSuccess.extractedDocumentType = field.text;
                    
                    break;
                }
            case DateOfBirth:
                {
                    field.text = [self getDateOfBirth:mbCombine];
                    self.idSuccess.extractedDateOfBirth = field.text;
                    [self.DOBPickerView setDate:[self getNsdate:field.text] animated:YES];
                    strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_erragelimitdateOfBirth", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Age of user is below minimum allowed age!", nil);
                    [self checkForAgeLimit:self.LbERDOB Message:strMessage Value:field.text FieldTag:DateOfBirth];
                    break;
                }
            case DateOfExpiration:
                {
                    field.text = [self getDateOfExpire:mbCombine];
                    self.idSuccess.extractedDateOfExpire = field.text;
                    [self.DOEPickerView setDate:[self getNsdate:field.text] animated:YES];
                    break;
                }
            case Nationality:
                {
                    field.text = [self getNationality:mbCombine];
                    self.idSuccess.extractedNation = field.text;
                    break;
                }
            case Issuer:
                {
                    field.text = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.issuer length] == 0) ? mbCombine.result.issuingAuthority : mbCombine.result.mrzResult.issuer : mbCombine.result.issuingAuthority;
                    self.idSuccess.extractedIssuer = field.text;
                    break;
                }
            default:
                break;
        }
    }
    [self showExtractedSuggestedPopup];
}

- (NSString*) getNationality:(MBBlinkIdCombinedRecognizer *) mbCombine {
    NSString *nation = @"";
    nation = (mbCombine.result.mrzResult) ? ([mbCombine.result.mrzResult.nationality length] == 0) ? mbCombine.result.nationality : mbCombine.result.mrzResult.nationality : mbCombine.result.nationality;
    if([nation length] == 0) nation = mbCombine.result.classInfo.countryName;
    return nation;
}

- (NSDate*) getNsdate:(NSString*) date {
    NSDate *setDate = [NSDate date];
    if([date length]>0) {
        NSString *dateStr = date;
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:VFY_IDENTITY_DATEFORMATE];
        setDate = [dateFormat dateFromString:dateStr];
    }
    return setDate;
}

- (NSString *) getDateOfBirth:(MBBlinkIdCombinedRecognizer *) mbCombine {
    NSString *combineString=@"";
    if(mbCombine.result.mrzResult){
        combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.mrzResult.dateOfBirth.day, mbCombine.result.mrzResult.dateOfBirth.month, mbCombine.result.mrzResult.dateOfBirth.year];
        if(mbCombine.result.mrzResult.dateOfBirth.month == 0 && mbCombine.result.mrzResult.dateOfBirth.day == 0 && mbCombine.result.mrzResult.dateOfBirth.year == 0){
            combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.dateOfBirth.day, mbCombine.result.dateOfBirth.month, mbCombine.result.dateOfBirth.year];
        }
    } else {
        combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.dateOfBirth.day, mbCombine.result.dateOfBirth.month, mbCombine.result.dateOfBirth.year];
    }
    return combineString;
}

- (NSString *) getDateOfExpire:(MBBlinkIdCombinedRecognizer *) mbCombine {
    NSString *combineString=@"";
    if(mbCombine.result.mrzResult){
        combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.mrzResult.dateOfExpiry.day, mbCombine.result.mrzResult.dateOfExpiry.month, mbCombine.result.mrzResult.dateOfExpiry.year];
        if(mbCombine.result.mrzResult.dateOfExpiry.month == 0 && mbCombine.result.mrzResult.dateOfExpiry.day == 0 && mbCombine.result.mrzResult.dateOfExpiry.year == 0){
            combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.dateOfExpiry.day, mbCombine.result.dateOfExpiry.month, mbCombine.result.dateOfExpiry.year];
        }
    } else {
        combineString = [NSString stringWithFormat:@"%ld/%ld/%ld",mbCombine.result.dateOfExpiry.day, mbCombine.result.dateOfExpiry.month, mbCombine.result.dateOfExpiry.year];
    }
    return combineString;
}

/**
  Add localization text on labels
*/
- (void) setLocalizationText {
    self.LbFName.text = NSLocalizedStringWithDefaultValue(@"mb_identity_firstname", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"FIRST NAME", nil);
    self.LbLName.text = NSLocalizedStringWithDefaultValue(@"mb_identity_lastname", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"LAST NAME", nil);
    self.LbGender.text = NSLocalizedStringWithDefaultValue(@"mb_identity_gender", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"GENDER", nil);
    self.LbADS.text = NSLocalizedStringWithDefaultValue(@"mb_identity_address", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"ADDRESS", nil);
    self.LbDNumber.text = NSLocalizedStringWithDefaultValue(@"mb_identity_documentNumber", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"DOCUMENT NUMBER", nil);
    self.LbDType.text = NSLocalizedStringWithDefaultValue(@"mb_identity_document_type", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"DOCUMENT TYPE", nil);
    self.LbDOB.text = NSLocalizedStringWithDefaultValue(@"mb_identity_dateOfBirth", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"DATE OF BIRTH", nil);
    self.LbDOE.text = NSLocalizedStringWithDefaultValue(@"mb_identity_dateOfExpiry", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"EXPIRATION DATE", nil);
    self.LbIssuer.text = NSLocalizedStringWithDefaultValue(@"mb_identity_issuer", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"ISSUER", nil);
    self.LbNation.text = NSLocalizedStringWithDefaultValue(@"mb_identity_nationality", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"NATIONALITY", nil);
    
    /* Set localization on button */
    [self.BtContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_identity_button_1", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Continue", nil) forState:UIControlStateNormal];
}

/**
  Set the label alignment as per the language
*/
- (void) setLabelAlignment {
    if([[self.sharedInstance language] isEqualToString:@"ar"]){
        [self.LbFName setTextAlignment:NSTextAlignmentRight];
        [self.LbLName setTextAlignment:NSTextAlignmentRight];
        [self.LbGender setTextAlignment:NSTextAlignmentRight];
        [self.LbADS setTextAlignment:NSTextAlignmentRight];
        [self.LbDNumber setTextAlignment:NSTextAlignmentRight];
        [self.LbDType setTextAlignment:NSTextAlignmentRight];
        [self.LbDOB setTextAlignment:NSTextAlignmentRight];
        [self.LbDOE setTextAlignment:NSTextAlignmentRight];
        [self.LbIssuer setTextAlignment:NSTextAlignmentRight];
        [self.LbNation setTextAlignment:NSTextAlignmentRight];
        //[self.LbFullName setTextAlignment:NSTextAlignmentRight];
        //set alignment on all textfield
        for (UITextField* field in self.fields) {
            [field setTextAlignment:NSTextAlignmentRight];
        }
        //set alignment on all textview
        [self.TvADS setTextAlignment:NSTextAlignmentRight];
        //set alignment on all error label
        [self.LbERFName setTextAlignment:NSTextAlignmentRight];
        [self.LbERLName setTextAlignment:NSTextAlignmentRight];
        [self.LbERGender setTextAlignment:NSTextAlignmentRight];
        [self.LbERADS setTextAlignment:NSTextAlignmentRight];
        [self.LbERDNumber setTextAlignment:NSTextAlignmentRight];
        [self.LbERDType setTextAlignment:NSTextAlignmentRight];
        [self.LbERDOB setTextAlignment:NSTextAlignmentRight];
        [self.LbERDOE setTextAlignment:NSTextAlignmentRight];
        [self.LbERIssuer setTextAlignment:NSTextAlignmentRight];
        [self.LbERNation setTextAlignment:NSTextAlignmentRight];
    }
}

/**
  Add Header title test or image
*/
-(void) CustomTitle {
    if([self.sharedInstance.headerTitleImage length]>0){
       [Utilities customTitleImage:self.navigationItem Logo:self.sharedInstance.headerTitleImage];
    } else if([self.sharedInstance.headerTitleText length]){
        [Utilities customTitleText:self.navigationItem TitleText:self.sharedInstance.headerTitleText FontColor:self.sharedInstance.headerTextColor];
    }
}

- (IBAction)BtnContinue:(id)sender {
    [self validationCheck];
    if([self.failedValidateCount count] == 0){
       [self CheckUpdatedInformation];
       [self updateScore];
       //[self printResult];
       [self showContinueSuggestedPopup];
    }
}

- (void) submitSuccess {
    [self callAudit];
    
    if(callDirectlyFlag == Directly) {
       [self.idGuide callClose:IDSuccessComplete PassValue:self.idSuccess];
    } else if(callDirectlyFlag == InDirectly) {
       UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
       VFYIDSelfieGuideWrapper *newView = [storyboard instantiateViewControllerWithIdentifier:VFY_SELFIE_STORYBOARD];
       newView.idSuccess = self.idSuccess;
       [self.navigationController pushViewController:newView animated:YES];
    }
}

/**
  Validation check method
*/
- (void)validationCheck {
    self.failedValidateCount = [NSMutableArray new];
    for (UITextField* field in self.fields) {
         [self emptyTextfieldValidation:field];
    }
    if ([self.TvADS.text isEqualToString:@""]) {
        [self.failedValidateCount addObject:[NSString stringWithFormat: @"%d", Address]];
        self.LbERADS.hidden = false;
        self.LbERADS.text = NSLocalizedStringWithDefaultValue(@"mb_identity_erraddress", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter address", nil);
        self.LbERADS.textColor = [UIColor redColor];
    } else {
        if(!self.LbERADS.hidden){
           self.LbERADS.hidden = true;
           self.LbERADS.text = @"";
        }
    }
}

/**
    Compare and update idsuccess
 */
- (void) CheckUpdatedInformation {
    //NSLog(@"%@",self.sharedInstance.idSuccess.documentNumber);
    for (UITextField* field in self.fields) {
         [self updateIdSuccessValues:field];
    }
}

/**
    Update idsuccess attributes
*/
- (void) updateIdSuccessValues :(UITextField*) textfield {
    switch (textfield.tag) {
        case FirstName:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedFirstName] != NSOrderedSame) {
                    self.idSuccess.firstNameEditedFlag = true;
                    self.idSuccess.editedFirstName = textfield.text;
                }
                break;
            }
        case LastName:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedLastName] != NSOrderedSame) {
                    self.idSuccess.lastNameEditedFlag = true;
                    self.idSuccess.editedLastName = textfield.text;
                }
                break;
            }
        case Gender:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedGender] != NSOrderedSame) {
                    self.idSuccess.genderEditedFlag = true;
                    self.idSuccess.editedGender = textfield.text;
                }
                break;
            }
        case DocumentNumber:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedIdDocumentNumber] != NSOrderedSame) {
                    self.idSuccess.idDocumentNumberEditedFlag = true;
                    self.idSuccess.editedIdDocumentNumber = textfield.text;
                }
                break;
            }
        case DocumentType:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedDocumentType] != NSOrderedSame) {
                    self.idSuccess.documentTypeEditedFlag = true;
                    self.idSuccess.editedDocumentType = textfield.text;
                }
                break;
            }
        case DateOfBirth:
            {
                //[self displayMessage:self.LbERDOB Message:@"DateOfBirth" Value:textfield.text FieldTag:DateOfBirth];
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedDateOfBirth] != NSOrderedSame){
                    self.idSuccess.dateOfBirthEditedFlag = true;
                    self.idSuccess.editedDateOfBirth = textfield.text;
                }
                break;
            }
        case DateOfExpiration:
            {
                //[self displayMessage:self.LbERDOE Message:@"DateOfExpiration" Value:textfield.text FieldTag:DateOfExpiration];
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedDateOfExpire] != NSOrderedSame){
                    self.idSuccess.dateOfExpireEditedFlag = true;
                    self.idSuccess.editedDateOfExpire = [NSString stringWithFormat:@"%@",textfield.text];
                }
                break;
            }
        case Nationality:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedNation] != NSOrderedSame) {
                    self.idSuccess.nationEditedFlag = true;
                    self.idSuccess.editedNation = [NSString stringWithFormat:@"%@",textfield.text];
                }
                break;
            }
        case Issuer:
            {
                if([textfield.text caseInsensitiveCompare:self.idSuccess.extractedIssuer] != NSOrderedSame) {
                    self.idSuccess.issuerEditedFlag = true;
                    self.idSuccess.editedIssuer = textfield.text;
                }
                break;
            }
        default:
            break;
    }
}

/**
      Validation as per the textfields
*/
- (void) emptyTextfieldValidation :(UITextField*) textfield {
    NSString *strMessage = [NSString string];
    switch (textfield.tag) {
        case FirstName:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errfirstname", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter firstname", nil);
                [self displayMessage:self.LbERFName Message:strMessage Value:textfield.text FieldTag:FirstName];
                break;
            }
        case LastName:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errlastname", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter lastname", nil);
                [self displayMessage:self.LbERLName Message:strMessage Value:textfield.text FieldTag:LastName];
                break;
            }
        case Gender:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errgender", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter gender", nil);
                [self displayMessage:self.LbERGender Message:strMessage Value:textfield.text FieldTag:Gender];
                break;
            }
        case DocumentNumber:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errdocumentNumber", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter document number", nil);
                [self displayMessage:self.LbERDNumber Message:strMessage Value:textfield.text FieldTag:DocumentNumber];
                break;
            }
        case DocumentType:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errdocumentType", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter document type", nil);
                [self displayMessage:self.LbERDType Message:strMessage Value:textfield.text FieldTag:DocumentType];
                break;
            }
        case DateOfBirth:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errdateOfBirth", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter date of birth", nil);
                [self displayMessage:self.LbERDOB Message:strMessage Value:textfield.text FieldTag:DateOfBirth];
                
                NSString  *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_erragelimitdateOfBirth", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Age of user is below minimum allowed age!", nil);
                [self checkForAgeLimit:self.LbERDOB Message:strMessage Value:textfield.text FieldTag:DateOfBirth];
                break;
            }
        case DateOfExpiration:
            {
                /* Uncomment to start validation
                 strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errdateOfExpiry", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter date of expire", nil);
                [self displayMessage:self.LbERDOE Message:strMessage Value:textfield.text FieldTag:DateOfExpiration];*/
                break;
            }
        case Nationality:
            {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errnationality", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter nationality", nil);
                [self displayMessage:self.LbERNation Message:strMessage Value:textfield.text FieldTag:Nationality];
                break;
            }
        case Issuer:
            {
                /*strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_errissuer", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter issuer", nil);
                [self displayMessage:self.LbERIssuer Message:strMessage Value:textfield.text FieldTag:Issuer]; */
                break;
            }
        default:
            break;
    }
}

- (void) displayMessage: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(successFieldNames) fieldTag {
    if ([value isEqualToString:@""] || [value isEqualToString:@"0/0/0"]) {
        [self.failedValidateCount addObject:[NSString stringWithFormat: @"%d", fieldTag]];
        labelName.hidden = false;
        //labelName.text = [NSString stringWithFormat:@"Please enter %@",message];
        labelName.text = message;
        labelName.textColor = [UIColor redColor];
    } else {
        if(!labelName.hidden){
           labelName.hidden = true;
           labelName.text = @"";
        }
    }
}

/**
  Add close button in navigation
*/
- (void) setCloseButton {
    UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] initWithTitle:@"Close" style:UIBarButtonItemStylePlain target:self action:@selector(BtClose:)];
    self.navigationItem.leftBarButtonItem = flipButton;
}

/**
  Add close button in navigation
*/
-(IBAction) BtClose:(id)sender {
    //[self dismissViewControllerAnimated:YES completion:nil];
    
    [self.idGuide callClose:IDSuccessWrapper];
}

/**
   Add border at bottom of testfield
 */
- (void) setBorder:(UITextField*) textfield {
    CALayer *border = [CALayer layer];
    CGFloat width = 0.3;
    border.borderColor = UIColor.darkGrayColor.CGColor;
    border.frame = CGRectMake(0, textfield.frame.size.height - width, textfield.frame.size.width, textfield.frame.size.height);
    border.borderWidth = width;
    [textfield.layer addSublayer:border];
    textfield.layer.masksToBounds = true;
}

/**
    Register keyboardnotification
*/
- (void)registerForKeyboardNotifications
{
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
/*- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your application might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, self.activeField.frame.origin) ) {
        CGPoint scrollPoint = CGPointMake(0.0, self.activeField.frame.origin.y-kbSize.height);
        //NSLog(@"scrollPoint %@",scrollPoint);
        NSLog(@"%@", NSStringFromCGPoint(scrollPoint));
        [self.scrollView setContentOffset:scrollPoint animated:YES];
    }
}*/

/**
    Adjust the view as per the keyboard appear
*/
- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    /*if currentFirstResponder is overlayed by the keyboard, move it so it bottom ends where the keyboard begins*/
    //if(self.currentFirstResponder){
        //keyboard origin in currentFirstResponderFrame
        CGPoint keyboardOrigin = [self.activeField convertPoint:kbFrame.origin fromView:nil];
    float spaceBetweenFirstResponderAndKeyboard = fabs(self.activeField.frame.size.height-keyboardOrigin.y);
        //only scroll the scrollview if keyboard overlays the first responder
        if(spaceBetweenFirstResponderAndKeyboard>0){
            //if i call setContentOffset:animate:YES it behaves differently, not sure why
            [UIView animateWithDuration:0.25 animations:^{
                //[self.scrollView setContentOffset:CGPointMake(0,self.scrollView.contentOffset.y+spaceBetweenFirstResponderAndKeyboard)];
                [self.scrollView setContentOffset:CGPointMake(0,self.scrollView.contentOffset.y)];
            }];
        }
    //}

    //set bottom inset to the keyboard height so you can still scroll the whole content

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbFrame.size.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

/** Keyboard hidden */
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    self.scrollView.contentInset = contentInsets;
    self.scrollView.scrollIndicatorInsets = contentInsets;
}

/** Assign the active field when editing begin */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.activeField = textField;
}

/** Unassign the active field when editing end */
- (void)textFieldDidEndEditing:(UITextField *)textField {
    self.activeField = nil;
    if(textField.tag == Nationality){
        NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_identity_errnationality", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter nationality", nil);
        [self displayMessage:self.LbERNation Message:strMessage Value:textField.text FieldTag:Nationality];
    }
}

/** Hide the keyboard on enter pressed */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

/** Add toolbar with done button in keyboard on textfield */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.translucent=NO;
    numberToolbar.barTintColor=[Utilities colorFromColorString:[self.sharedInstance headerColor]];
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(textFieldDoneButton)];
    [done setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: self.headerFontColor,  NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    [done setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor],  NSForegroundColorAttributeName,nil] forState:UIControlStateHighlighted];
    numberToolbar.items = [NSArray arrayWithObjects:
                                  [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                                  [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                                  done,nil];
    textField.inputAccessoryView = numberToolbar;
    return YES;
}

/** Resign responder from active field */
- (void)textFieldDoneButton {
    [self.activeField resignFirstResponder];
    /* for (UITextField* field in self.fields) { [field resignFirstResponder]; } */
}

/** Add toolbar with done button in keyboard on textview */
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.translucent=NO;
    numberToolbar.barTintColor=[Utilities colorFromColorString:[self.sharedInstance headerColor]];
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(textViewDoneButton)];
    [done setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: self.headerFontColor,  NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];
    numberToolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], done,nil];
    textView.inputAccessoryView = numberToolbar;
    return YES;
}

/** Resign responder from active field */
- (void)textViewDoneButton {
    [self.TvADS resignFirstResponder];
}
/**
  Add dynamic validation on editing complete
 */
- (void)textViewDidEndEditing:(UITextView *)textView {
    if ([self.TvADS.text isEqualToString:@""]) {
        [self.failedValidateCount addObject:[NSString stringWithFormat: @"%d", Address]];
        self.LbERADS.hidden = false;
        self.LbERADS.text = NSLocalizedStringWithDefaultValue(@"mb_identity_erraddress", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter address", nil);
        self.LbERADS.textColor = [UIColor redColor];
    } else {
        if(!self.LbERADS.hidden){
           self.LbERADS.hidden = true;
           self.LbERADS.text = @"";
        }
    }
}

/**
 Add address pickerview method
*/
- (void) addGenderPickerView {
    self.genderPickerView = [[UIPickerView alloc] init];
    self.genderPickerView.delegate = (id)self;
    self.genderPickerView.dataSource = (id)self;
    self.TfGender.inputView = self.genderPickerView;
    UIToolbar *toolBarGender = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [toolBarGender setBarTintColor:self.headerColor];
    [toolBarGender setTintColor:self.headerFontColor];
    UIBarButtonItem *doneGender =[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dismissedGender)]; //When clicked "Done" the UIPickerView disappears.
    UIBarButtonItem *spaceGender = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBarGender setItems:[NSArray arrayWithObjects:spaceGender,doneGender,nil]];
    [self.TfGender setInputAccessoryView:toolBarGender];
}

/**
 Pickerview dismissed method
*/
- (void)dismissedGender{
    [self.TfGender resignFirstResponder];
}

/**
 Add address pickerview method
*/
- (void) addNationalityPickerView {
    self.natlPickerView = [[UIPickerView alloc] init];
    self.natlPickerView.delegate = (id)self;
    self.natlPickerView.dataSource = (id)self;
    self.TfCountry.inputView = self.natlPickerView;
    UIToolbar *toolBarCnty = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [toolBarCnty setBarTintColor:self.headerColor];
    [toolBarCnty setTintColor:self.headerFontColor];
    UIBarButtonItem *doneCnty =[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dismissedCountryPicker)]; //When clicked "Done" the UIPickerView disappears.
    UIBarButtonItem *spaceCnty = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBarCnty setItems:[NSArray arrayWithObjects:spaceCnty,doneCnty,nil]];
    [self.TfCountry setInputAccessoryView:toolBarCnty];
}

/**
 Pickerview dismissed method
*/
- (void)dismissedCountryPicker{
    [self.TvADS resignFirstResponder];
}

- (void)dismissedDOBPicker {
    [self.TfDOB resignFirstResponder];
}

- (void)dismissedDOEPicker {
    [self.TfDOE resignFirstResponder];
}

/**
 Add DOB pickerview method
*/
- (void) addDOBPickerView {
    self.DOBPickerView = [[UIDatePicker alloc] init];
    //[self.DOBPickerView setDate:[NSDate date]];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:-100];
    NSDate *minDate = [cal dateByAddingComponents:comps toDate:[NSDate date]  options:0];
    //NSDate *maxDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
    NSDate *maxDate = [NSDate date];
    
    self.DOBPickerView.minimumDate = minDate;
    self.DOBPickerView.maximumDate = maxDate;
    
    self.DOBPickerView.datePickerMode = UIDatePickerModeDate;
    [self.DOBPickerView addTarget:self action:@selector(dateOfBirthTextField:) forControlEvents:UIControlEventValueChanged];
    self.TfDOB.inputView = self.DOBPickerView;
    UIToolbar *toolBarDOB = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [toolBarDOB setBarTintColor:self.headerColor];
    [toolBarDOB setTintColor:self.headerFontColor];
    UIBarButtonItem *doneDOB =[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dismissedDOBPicker)]; //When clicked "Done" the UIPickerView disappears.
    UIBarButtonItem *spaceDOB = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBarDOB setItems:[NSArray arrayWithObjects:spaceDOB,doneDOB,nil]];
    [self.TfDOB setInputAccessoryView:toolBarDOB];
}

/**
  Update value for DOB pickerview in textfield
*/
-(void) dateOfBirthTextField:(id)sender
{
    UIDatePicker *picker = (UIDatePicker*)self.TfDOB.inputView;
    //[picker setMaximumDate:[NSDate date]];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSDate *eventDate = picker.date;
    [dateFormat setDateFormat:VFY_IDENTITY_DATEFORMATE];
    NSString *dateString = [dateFormat stringFromDate:eventDate];
    self.TfDOB.text = [NSString stringWithFormat:@"%@",dateString];
    
   NSString  *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationIdentity_erragelimitdateOfBirth", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Age of user is below minimum allowed age!", nil);
    [self checkForAgeLimit:self.LbERDOB Message:strMessage Value:self.TfDOB.text FieldTag:DateOfBirth];
}

/**
  Add DOE pickerview method
*/
- (void) addDOEPickerView {
    self.DOEPickerView = [[UIDatePicker alloc] init];
    [self.DOEPickerView setDate:[NSDate date]];
    self.DOEPickerView.minimumDate = [NSDate date];
    self.DOEPickerView.datePickerMode = UIDatePickerModeDate;
    [self.DOEPickerView addTarget:self action:@selector(dateOfExpireTextField:) forControlEvents:UIControlEventValueChanged];
    self.TfDOE.inputView = self.DOEPickerView;
    UIToolbar *toolBarDOE = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    [toolBarDOE setBarTintColor:self.headerColor];
    [toolBarDOE setTintColor:self.headerFontColor];
    UIBarButtonItem *doneDOE =[[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(dismissedDOEPicker)]; //When clicked "Done" the UIPickerView disappears.
    UIBarButtonItem *spaceDOE = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [toolBarDOE setItems:[NSArray arrayWithObjects:spaceDOE,doneDOE,nil]];
    [self.TfDOE setInputAccessoryView:toolBarDOE];
}

/**
  Update value for DOB pickerview in textfield
*/
-(void) dateOfExpireTextField:(id)sender {
    UIDatePicker *picker = (UIDatePicker*)self.TfDOE.inputView;
    //[picker setMaximumDate:[NSDate date]];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    NSDate *eventDate = picker.date;
    [dateFormat setDateFormat:VFY_IDENTITY_DATEFORMATE];
    NSString *dateString = [dateFormat stringFromDate:eventDate];
    self.TfDOE.text = [NSString stringWithFormat:@"%@",dateString];
    /*NSString  *strMessage = NSLocalizedStringWithDefaultValue(@"mb_identity_errdateOfExpiry", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please enter date of expire", nil);
    [self displayMessage:self.LbERDOE Message:strMessage Value:self.TfDOE.text FieldTag:DateOfExpiration];*/
}

/**
  Call the suggestion popup when assign the extracted value
*/
- (void) showExtractedSuggestedPopup {
    bool suggestionFlag = self.sharedInstance.suggestionValidation;
    NSString *accountName = [NSString string];
    NSString *cardName = [NSString string];
    if([self.sharedInstance.accountOwnerFirstName length]>0 || [self.sharedInstance.accountOwnerLastName length] > 0){
        accountName = [NSString stringWithFormat:@"%@ %@", self.sharedInstance.accountOwnerFirstName, self.sharedInstance.accountOwnerLastName];
        accountName = [accountName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    if([self.sharedInstance.cardOwnerFirstName length]>0 || [self.sharedInstance.cardOwnerLastName length] > 0){
        cardName = [NSString stringWithFormat:@"%@ %@", self.sharedInstance.cardOwnerFirstName, self.sharedInstance.cardOwnerLastName];
        cardName = [cardName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    NSString *extractedIdName = [NSString stringWithFormat:@"%@ %@", self.idSuccess.extractedFirstName, self.idSuccess.extractedLastName];
    extractedIdName = [extractedIdName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if(suggestionFlag && ([cardName length] > 0 || [accountName length] > 0)){
        if(([cardName caseInsensitiveCompare:extractedIdName] != NSOrderedSame) && ([accountName caseInsensitiveCompare:extractedIdName] != NSOrderedSame)){
            [self pushSuggestedPopup];
        } else if([extractedIdName length] == 0) {
            [self pushSuggestedPopup];
        }
    }
}

/**
  Push the suggestion popup
*/
- (void) pushSuggestedPopup {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
    VFYSuggestionPopup *vc = [storyboard instantiateViewControllerWithIdentifier:@"VFYSuggestion"];
    vc.popupSelf = (id)self;
    vc.callMethodFlag = IDExtract;
    vc.extFirstName = self.idSuccess.extractedFirstName;
    vc.extLastName = self.idSuccess.extractedLastName;
    vc.accOwnerFrstName = self.sharedInstance.accountOwnerFirstName;
    vc.accOwnerLstName = self.sharedInstance.accountOwnerLastName;
    vc.crdOwnerFrstName = self.sharedInstance.cardOwnerFirstName;
    vc.crdOwnerLstName = self.sharedInstance.cardOwnerLastName;
    [self presentViewController:vc animated:YES completion:nil];
}
/**
  Call the suggestion popup when submit the form
*/
- (void) showContinueSuggestedPopup {
    bool suggestionFlag = self.sharedInstance.suggestionValidation;
    bool isEditedCardName = false;
    if(self.idSuccess.firstNameEditedFlag || self.idSuccess.lastNameEditedFlag){
       isEditedCardName = true;
    }
    NSString *accountName = [NSString string];
    NSString *cardName = [NSString string];
    if([self.sharedInstance.accountOwnerFirstName length]>0 || [self.sharedInstance.accountOwnerLastName length] > 0){
        accountName = [NSString stringWithFormat:@"%@ %@", self.sharedInstance.accountOwnerFirstName, self.sharedInstance.accountOwnerLastName];
        accountName = [accountName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    if([self.sharedInstance.cardOwnerFirstName length]>0 || [self.sharedInstance.cardOwnerLastName length] > 0){
        cardName = [NSString stringWithFormat:@"%@ %@", self.sharedInstance.cardOwnerFirstName, self.sharedInstance.cardOwnerLastName];
        cardName = [cardName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    NSString *extractedIdName = [NSString stringWithFormat:@"%@ %@", self.idSuccess.editedFirstName, self.idSuccess.editedLastName];
    extractedIdName = [extractedIdName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //if(suggestionFlag && [accountName length] > 0 && isEditedCardName){
    if(suggestionFlag && ([cardName length] > 0 || [accountName length] > 0) && isEditedCardName){
        if(([cardName caseInsensitiveCompare:extractedIdName] != NSOrderedSame) && ([accountName caseInsensitiveCompare:extractedIdName] != NSOrderedSame)){
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
            VFYSuggestionPopup *vc = [storyboard instantiateViewControllerWithIdentifier:@"VFYSuggestion"];
            vc.popupSelf = (id)self;
            vc.callMethodFlag = IDContinue;
            vc.extFirstName = self.idSuccess.extractedFirstName;
            vc.extLastName = self.idSuccess.extractedLastName;
            vc.accOwnerFrstName = self.sharedInstance.accountOwnerFirstName;
            vc.accOwnerLstName = self.sharedInstance.accountOwnerLastName;
            vc.crdOwnerFrstName = self.sharedInstance.cardOwnerFirstName;
            vc.crdOwnerLstName = self.sharedInstance.cardOwnerLastName;
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            [self submitSuccess];
        }
    } else {
        [self submitSuccess];
    }
}

/**
  Handle the callback from the popup view
*/
- (void) callBackFromPopupClose:(popupCallFromMethod)methodName PassValue:(NSString*)passValue {
    if(methodName == IDExtract){
        if(passValue != nil){
            UITextField *fstField = [self.fields objectAtIndex:0];
            UITextField *sndField = [self.fields objectAtIndex:1];
            fstField.text = [[passValue valueForKey:@"firstname"] capitalizedString];
            sndField.text = [[passValue valueForKey:@"lastname"] capitalizedString];
        }
    } else if(methodName == IDContinue){
        if(passValue != nil){
            UITextField *fstField = [self.fields objectAtIndex:0];
            UITextField *sndField = [self.fields objectAtIndex:1];
            fstField.text = [[passValue valueForKey:@"firstname"] capitalizedString];
            sndField.text = [[passValue valueForKey:@"lastname"] capitalizedString];
            self.idSuccess.editedFirstName = [[passValue valueForKey:@"firstname"] capitalizedString];
            self.idSuccess.editedLastName = [[passValue valueForKey:@"lastname"] capitalizedString];
        }
        [self submitSuccess];
    }
}

/**
  Check and update the score
*/
- (void) updateScore {
    if(self.idSuccess.dateOfBirthEditedFlag){
        self.idSuccess.dateOfBirthScore = 0;
    } else {
        self.idSuccess.dateOfBirthScore = 100;
    }
    if(self.idSuccess.idDocumentNumberEditedFlag){
        self.idSuccess.documentNumberScore = 0;
    } else {
        self.idSuccess.documentNumberScore = 100;
    }
}

/**
   Display the card validation message
*/
- (void) checkForAgeLimit: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(successFieldNames) fieldTag {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:VFY_IDENTITY_DATEFORMATE];
    NSDate *date = [dateFormatter dateFromString:value];
    if (![value isEqualToString:@""] && ![value isEqualToString:@"0/0/0"]) {
        if ([self validateDOB:date]) {
            [self.failedValidateCount addObject:[NSString stringWithFormat: @"%d", fieldTag]];
            labelName.hidden = false;
            labelName.text = message;
            labelName.textColor = [UIColor redColor];
        } else {
            if(!labelName.hidden){
               labelName.hidden = true;
               labelName.text = @"";
            }
        }
    }
}

/**
  Validate date of birth
*/
- (bool) validateDOB:(NSDate *)dateDOB {
    NSInteger currYear;
    NSInteger dobirthYear;
    NSInteger age = 0;
    bool returnValue=false;
    NSInteger ageLimit;
    if([[self.sharedInstance minimumAgeLimit] length] > 0){
        ageLimit = [[self.sharedInstance minimumAgeLimit] integerValue];
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];
    NSString *currentYear = [formatter stringFromDate:[NSDate date]];
    NSString *dobYear = [formatter stringFromDate:dateDOB];
    if([currentYear length] > 0 && [dobYear length] > 0){
        currYear = [currentYear integerValue];
        dobirthYear = [dobYear integerValue];
        age = currYear - dobirthYear;
        if(getDaysInYear([NSDate date]) < getDaysInYear(dateDOB)){
            age--;
        }
        if(age < ageLimit){
            returnValue = true;
        }
    }
    return returnValue;
}

/**
  Get the days of years
*/
/*NSInteger getDaysInYear(NSDate* date) {
    NSCalendar *currentCalendar = [NSCalendar currentCalendar];
    NSDate *today = date;
    NSInteger dc = [currentCalendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:today];
    return dc;
} */

/**
    Get the document type as per the MRZ result and user info
*/
- (NSString *) getDocumentType :(MBBlinkIdCombinedRecognizer *) mbCombine {
    NSString *setDocumentType = @"";
    if(mbCombine.result.mrzResult) {
        NSString *dcType =  [self getDocumentTypeFrmMRZ:mbCombine.result.mrzResult.documentType];
        if([dcType isEqualToString:@"Unknown"]){
            setDocumentType = [self getDocumentTypeFrmUserInfo:mbCombine.result.classInfo.type];
        } else {
            setDocumentType = dcType;
        }
    } else if(mbCombine.result.classInfo) {
        setDocumentType = [self getDocumentTypeFrmUserInfo:mbCombine.result.classInfo.type];
    }
    return setDocumentType;
}

/**
    Get the document type as per the MRZ result
*/
- (NSString *) getDocumentTypeFrmMRZ :(NSInteger) documentType {
    NSString *setDocumentType = @"Unknown";
    switch (documentType) {
        case 0:
            setDocumentType = @"Unknown";
            break;
        case 1:
            setDocumentType = @"IdentityCard";
            break;
        case 2:
            setDocumentType = @"Passport";
            break;
        case 3:
            setDocumentType = @"Visa";
            break;
        case 4:
            setDocumentType = @"GreenCard";
            break;
        case 5:
            setDocumentType = @"Malaysian PASS IMM13P";
            break;
        case 6:
            setDocumentType = @"One liner ISO DL";
            break;
        case 7:
            setDocumentType = @"Internal TravelDocument";
            break;
        default:
            break;
    }
    return setDocumentType;
}

/**
    Get the document type as per the user info
*/
- (NSString *) getDocumentTypeFrmUserInfo :(NSInteger) documentType {
    NSString *setDocumentType = @"Unknown";
    switch (documentType) {
        case 0:
            setDocumentType = @"Unknown";
            break;
        case 1:
            setDocumentType = @"Consular Id Card";
            break;
        case 2:
            setDocumentType = @"Driver's License";
            break;
        case 3:
            setDocumentType = @"Public Services Card";
            break;
        case 4:
            setDocumentType = @"Employment Pass";
            break;
        case 5:
            setDocumentType = @"FinCard";
            break;
        case 6:
            setDocumentType = @"Identity Card";
            break;
        case 7:
            setDocumentType = @"Multipurpose Id";
            break;
        case 8:
            setDocumentType = @"MyKad";
            break;
        case 9:
            setDocumentType = @"MyKid";
            break;
        case 10:
            setDocumentType = @"MyPR";
            break;
        case 11:
            setDocumentType = @"MyTentera";
            break;
        case 12:
            setDocumentType = @"PanCard";
            break;
         case 13:
            setDocumentType = @"Professional Id";
            break;
         case 14:
            setDocumentType = @"PublicServices Card";
            break;
         case 15:
            setDocumentType = @"Residence Permit";
            break;
         case 16:
            setDocumentType = @"Resident Id";
            break;
         case 17:
            setDocumentType = @"Temporary Residence Id";
            break;
         case 18:
            setDocumentType = @"Voter Id";
            break;
         case 19:
            setDocumentType = @"Work Permit";
            break;
         case 20:
            setDocumentType = @"iKad";
            break;
         case 21:
            setDocumentType = @"Military Id";
            break;
         case 22:
            setDocumentType = @"MyKas";
            break;
         case 23:
            setDocumentType = @"SocialSecurity Card";
            break;
         case 24:
            setDocumentType = @"HealthInsurance Card";
            break;
         default:
            break;
    }
    return setDocumentType;
}

- (void) callAudit {
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    self.auditEventDuration = CACurrentMediaTime() - self.auditEventDuration;
    if(self.auditEventDuration) {
        NSString *eventDuration = [Utilities stringFromTimeInterval:self.auditEventDuration];
        NSString *scanDuration = [Utilities stringFromTimeInterval:self.auditScanDuration];
        [setting setValue:eventDuration forKey:@"audit_event_duration"];
        [setting setValue:scanDuration forKey:@"audit_scan_Duration"];
    } else {
        [setting setValue:@"" forKey:@"audit_event_duration"];
        [setting setValue:@"" forKey:@"audit_scan_Duration"];
    }
    [VFYAuditManager idSuccessAudit:self.idSuccess settings:setting completed:^(NSString *response) {
        NSLog(@"Id success response %@",response);
    } failure:^(NSError *error){
        NSLog(@"Id success response error : %@",error);
    }];
}

#pragma mark - UIPickerViewDataSource

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (pickerView == self.natlPickerView || pickerView == self.genderPickerView) {
        return 1;
    }
    return 0;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView == self.natlPickerView) {
        return [self.countryNames count];
    }
    if(pickerView == self.genderPickerView){
        return [self.genders count];
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView == self.natlPickerView) {
        return self.countryNames[row];
    }
    if(pickerView == self.genderPickerView){
        return self.genders[row];
    }
    return nil;
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (pickerView == self.natlPickerView) {
        if(row != 0){
            self.TfCountry.text = self.countryNames[row];
        }
    }
    if(pickerView == self.genderPickerView){
        if(row != 0){
            self.TfGender.text = self.genders[row];
        }
    }
}

- (void) setGender {
    self.genders = @[@"Select", @"Male", @"Female", @"Non-binary"];
}

- (void) setCountry
{
    // Country code
    self.countryNames = @[
    @"Select",@"Afghanistan", @"Albania", @"Algeria",
    @"American Samoa", @"Andorra",
    @"Angola", @"Anguilla", @"Antigua and Barbuda",
    @"Argentina", @"Armenia",
    @"Aruba", @"Ascension",
    @"Australia", @"Australian External Territories",
    @"Austria", @"Azerbaijan",
    @"Bahamas", @"Bahrain",
    @"Bangladesh", @"Barbados",
    @"Barbuda", @"Belarus",
    @"Belgium", @"Belize",
    @"Benin", @"Bermuda",
    @"Bhutan", @"Bolivia",
    @"Bosnia and Herzegovina",
    @"Botswana", @"Brazil",
    @"British Indian Ocean Territory",
    @"British Virgin Islands",
    @"Brunei", @"Bulgaria",
    @"Burkina Faso", @"Burundi",
    @"Cambodia", @"Cameroon",
    @"Canada", @"Cape Verde",
    @"Cayman Islands", @"Central African Republic",
    @"Chad", @"Chile", @"China",
    @"Christmas Island", @"Cocos-Keeling Islands",
    @"Colombia", @"Comoros",
    @"Congo", @"Congo, Dem. Rep. of (Zaire)",
    @"Cook Islands", @"Costa Rica",
    @"Ivory Coast", @"Croatia",
    @"Cuba", @"Curacao",
    @"Cyprus", @"Czech Republic",
    @"Denmark", @"Diego Garcia",
    @"Djibouti", @"Dominica",
    @"Dominican Republic", @"East Timor",
    @"Easter Island", @"Ecuador",
    @"Egypt", @"El Salvador",
    @"Equatorial Guinea", @"Eritrea",
    @"Estonia", @"Ethiopia",
    @"Falkland Islands", @"Faroe Islands",
    @"Fiji",
    @"Finland",
    @"France",
    @"French Antilles",
    @"French Guiana",
    @"French Polynesia",
    @"Gabon",
    @"Gambia",
    @"Georgia",
    @"Germany",
    @"Ghana",
    @"Gibraltar",
    @"Greece",
    @"Greenland",
    @"Grenada",
    @"Guadeloupe",
    @"Guam",
    @"Guatemala",
    @"Guinea",
    @"Guinea-Bissau",
    @"Guyana",
    @"Haiti",
    @"Honduras",
    @"Hong Kong SAR China",
    @"Hungary",
    @"Iceland",
    @"India",
    @"Indonesia",
    @"Iran",
    @"Iraq",
    @"Ireland",
    @"Israel",
    @"Italy",
    @"Jamaica",
    @"Japan",
    @"Jordan",
    @"Kazakhstan",
    @"Kenya",
    @"Kiribati",
    @"North Korea",
    @"South Korea",
    @"Kuwait",
    @"Kyrgyzstan",
    @"Laos",
    @"Latvia",
    @"Lebanon",
    @"Lesotho",
    @"Liberia",
    @"Libya",
    @"Liechtenstein",
    @"Lithuania",
    @"Luxembourg",
    @"Macau SAR China",
    @"Macedonia",
    @"Madagascar",
    @"Malawi",
    @"Malaysia",
    @"Maldives",
    @"Mali",
    @"Malta",
    @"Marshall Islands",
    @"Martinique",
    @"Mauritania",
    @"Mauritius",
    @"Mayotte",
    @"Mexico",
    @"Micronesia",
    @"Midway Island",
    @"Micronesia",
    @"Moldova",
    @"Monaco",
    @"Mongolia",
    @"Montenegro",
    @"Montserrat",
    @"Morocco" ,
    @"Myanmar",
    @"Namibia",
    @"Nauru",
    @"Nepal",
    @"Netherlands",
    @"Netherlands Antilles",
    @"Nevis",
    @"New Caledonia",
    @"New Zealand",
    @"Nicaragua",
    @"Niger",
    @"Nigeria",
    @"Niue",
    @"Norfolk Island",
    @"Northern Mariana Islands",
    @"Norway",
    @"Oman" ,
    @"Pakistan",
    @"Palau"                                        ,
    @"Palestinian Territory"                        ,
    @"Panama"                                       ,
    @"Papua New Guinea"                             ,
    @"Paraguay"                                     ,
    @"Peru"                                         ,
    @"Philippines"                                  ,
    @"Poland"                                       ,
    @"Portugal"                                     ,
    @"Puerto Rico"                                  ,
    @"Puerto Rico"                                  ,
    @"Qatar"                                        ,
    @"Reunion"                                      ,
    @"Romania"                                      ,
    @"Russia"                                       ,
    @"Rwanda"                                       ,
    @"Samoa"                                        ,
    @"San Marino"                                   ,
    @"Saudi Arabia"                                 ,
    @"Senegal"                                      ,
    @"Serbia"                                       ,
    @"Seychelles"                                   ,
    @"Sierra Leone"                                 ,
    @"Singapore"                                    ,
    @"Slovakia"                                     ,
    @"Slovenia",
    @"Solomon Islands",
    @"South Africa",
    @"South Georgia and the South Sandwich Islands",
    @"Spain",
    @"Sri Lanka",
    @"Sudan",
    @"Suriname",
    @"Swaziland",
    @"Sweden",
    @"Switzerland",
    @"Syria",
    @"Taiwan",
    @"Tajikistan",
    @"Tanzania",
    @"Thailand",
    @"Timor Leste",
    @"Togo",
    @"Tokelau",
    @"Tonga",
    @"Trinidad and Tobago",
    @"Tunisia",
    @"Turkey",
    @"Turkmenistan",
    @"Turks and Caicos Islands",
    @"Tuvalu",
    @"Uganda",
    @"Ukraine", @"United Arab Emirates",
    @"United Kingdom", @"United States",
    @"Uruguay", @"U.S. Virgin Islands",
    @"Uzbekistan", @"Vanuatu",
    @"Venezuela", @"Vietnam",
    @"Wake Island", @"Wallis and Futuna",
    @"Yemen", @"Zambia", @"Zanzibar",@"Zimbabwe"
    ];
}

@end
