//
//  VFYCardGuideWrapper.m
//  Verif-y
//
//  Created by MTN on 19/10/20.
//

#import "VFYCardSuccessWrapper.h"
#import "Utilities.h"
#import "VFYConstant.h"
#import "VFYButton.h"
#import "Luhn.h"
#import "VFYSuggestionPopup.h"
#import "VFYAuditManager.h"

@interface VFYCardSuccessWrapper()
{

}

/** IBoutlet for labels */
@property (weak, nonatomic) IBOutlet UILabel *LbCardNumber;
@property (weak, nonatomic) IBOutlet UILabel *LbCardName;
@property (weak, nonatomic) IBOutlet UILabel *LbValidThru;
@property (weak, nonatomic) IBOutlet UILabel *LbCardCvv;
/** IBoutlet for error labels */
@property (weak, nonatomic) IBOutlet UILabel *LbErNumber;
@property (weak, nonatomic) IBOutlet UILabel *LbErName;
@property (weak, nonatomic) IBOutlet UILabel *LbErValid;
@property (weak, nonatomic) IBOutlet UILabel *LbErCvv;
/** IBoutlet for all UITextfields */
@property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *cardFields;
/** IBoutlet for UIImageView */
@property (nonatomic, weak) IBOutlet UIImageView *cardImage;
@property (nonatomic, weak) IBOutlet UIStackView *cvvStack;
/** IBoutlet for branding */
@property (weak, nonatomic) IBOutlet VFYButton *BTNContinue;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoPow;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoBy;
@property (weak, nonatomic) IBOutlet UIScrollView *BodyScrollView;
/** Miscellaneous variable*/
@property (nonatomic) BOOL cvvFlag;
@property (nonatomic) BOOL cardImageFlag;
@property (nonatomic, strong) NSMutableArray *failedValidateCount;
/** IBoutlet for extra varibles */
@property (weak, nonatomic) IBOutlet UITextField *TfValidThru;
@property (weak, nonatomic) IBOutlet UITextField *activeField;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) NSArray *validThruMonth;
@property (nonatomic, strong) NSArray *validThruYear;
@property (nonatomic, strong) NSString *selectMonth;
@property (nonatomic, strong) NSString *selectYear;
/** Variable related to picker */
@property (nonatomic, strong) UIPickerView *VldThruPickerView;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYCardSuccessWrapper


- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 13.0, *)) {
         self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    self.failedValidateCount = [NSMutableArray new];
    self.sharedInstance = [VFYVerifyApp sharedInstance];
    self.selectYear = [NSString string];
    self.selectMonth = [NSString string];
    [self setLocalizationText];
    [self CustomTitle];
    [self setBrandingColor];
    self.cvvFlag = false;
    self.cardImageFlag = false;
    [self hideViews];
    [self registerForKeyboardNotifications];
    //[self setCloseButton];
    [self setValues];
    [self setLabelAlignment];
}

-(void)dismissedValidThru {
    [self.TfValidThru resignFirstResponder];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void) viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}

/** Show/hide views */
- (void) hideViews {
    if(self.cvvFlag)self.cvvStack.hidden = true;
    if(self.cardImageFlag)self.cardImage.hidden = true;
}

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

/** Add localization text on labels */
- (void) setLocalizationText {
    self.LbCardNumber.text = NSLocalizedStringWithDefaultValue(@"mb_card_scan_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"CARD NUMBER", nil);
    self.LbCardName.text = NSLocalizedStringWithDefaultValue(@"mb_card_cardholder_name", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"NAME", nil);
    self.LbValidThru.text = NSLocalizedStringWithDefaultValue(@"mb_card_valid_thru", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"VALID THRU", nil);
    self.LbCardCvv.text = NSLocalizedStringWithDefaultValue(@"mb_card_scan_cvv", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"CVV", nil);
    [self.BTNContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_card_scan_button", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Continue", nil) forState:UIControlStateNormal];
}

/** 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];
    }
}

/** Add color to branding and corner button */
- (void) setBrandingColor {
    /* Set navigation appearance */
    [[UINavigationBar appearance] setBarTintColor:[Utilities colorFromColorString:[self.sharedInstance headerColor]]]; //header background
    [[UINavigationBar appearance] setTintColor:[Utilities colorFromColorString:[self.sharedInstance headerTextColor]]]; //back button
    [[UINavigationBar appearance] setTranslucent:false];
    NSDictionary *attributes = @{ NSForegroundColorAttributeName : [Utilities colorFromColorString:[self.sharedInstance headerTextColor]], NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Bold" size:17] }; //Title text color
    [[UINavigationBar appearance] setTitleTextAttributes:attributes];
    /* Set page appearance*/
    [[UILabel appearance] setTextColor:[Utilities colorFromColorString:self.sharedInstance.bodyTextColor]];
    [[UITextField appearance] setTextColor:[Utilities colorFromColorString:self.sharedInstance.bodyTextColor]];
    [[UITextView appearance] setTextColor:[Utilities colorFromColorString:self.sharedInstance.bodyTextColor]];
    [[UIButton appearance] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.scrollView setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    //[self.CardTitle setTextColor:[Utilities colorFromColorString:self.sharedInstance.bodyTitleColor]];
    
    /* Set color to the branding logo */
    [self.LbLogoPow setTextColor:[Utilities colorFromColorString:VFY_LOGO_POWER]];
    [self.LbLogoBy setTextColor:[Utilities colorFromColorString:VFY_LOGO_BY]];
    /* Set button style */
    [self.BTNContinue animateOnPress:YES borderColor:[Utilities colorFromColorString:[self.sharedInstance buttonBorderColor]] backGroundColor:[Utilities colorFromColorString:[self.sharedInstance buttonBackgroundColor]] textColor:[Utilities colorFromColorString:[self.sharedInstance buttonTextColor]]];
}

/** 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;
}

/**
  Set the label alignment as per the language
*/
- (void) setLabelAlignment {
    if([[self.sharedInstance language] isEqualToString:@"ar"]){
        [self.LbCardNumber setTextAlignment:NSTextAlignmentRight];
        [self.LbCardName setTextAlignment:NSTextAlignmentRight];
        [self.LbValidThru setTextAlignment:NSTextAlignmentRight];
        [self.LbCardCvv setTextAlignment:NSTextAlignmentRight];
        //set alignment on all textfield
        for (UITextField* field in self.cardFields) {
            [field setTextAlignment:NSTextAlignmentRight];
        }
        //set alignment on all error label
        [self.LbErNumber setTextAlignment:NSTextAlignmentRight];
        [self.LbErName setTextAlignment:NSTextAlignmentRight];
        [self.LbErValid setTextAlignment:NSTextAlignmentRight];
        [self.LbErCvv setTextAlignment:NSTextAlignmentRight];
    }
}

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

/*- (void) nameSuggestionCheck {
    bool suggestionFlag = self.sharedInstance.suggestionValidation;
    bool isEditedCardName = self.resultCard.editedCardHolderName;
    NSString *accountName = self.sharedInstance.accountOwner;
    NSString *extractedCardName = self.resultCard.extractedCardHolderName;
    NSString *editedCardName = self.resultCard.editedCardHolderName;
    NSString *accName_ExtractName_Score = [NSString string];
    NSString *accName_EditedName_Score = [NSString string];
    NSString *extractName_EditedName_Score = [NSString string];
    
    accName_ExtractName_Score = ([accountName caseInsensitiveCompare:extractedCardName] == NSOrderedSame) ? @"100" : @"0";
    if(isEditedCardName){
        accName_EditedName_Score = ([accountName caseInsensitiveCompare:editedCardName] == NSOrderedSame) ? @"100" : @"0";
        extractName_EditedName_Score = ([extractedCardName caseInsensitiveCompare:editedCardName] == NSOrderedSame) ? @"100" : @"0";
    }
} */

/** Validation check method */
- (void)validationCheck {
    self.failedValidateCount = [NSMutableArray new];
    for (UITextField* field in self.cardFields) {
         [self emptyTextfieldValidation:field];
    }
}

/**
 Validation as per the textfields
*/
- (void) emptyTextfieldValidation :(UITextField*) textfield {
    NSString *strMessage = [NSString string];
    switch (textfield.tag) {
        case CardNumber: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_correct_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please fill correct card number", nil);
                [self displayMessage:self.LbErNumber Message:strMessage Value:textfield.text FieldTag:CardNumber];
                NSString *strMsg = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Incorrect card number", nil);
                [self invalidCardMessage:self.LbErNumber Message:strMsg Value:textfield.text FieldTag:CardNumber];
                break;
            }
        case CardName: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_card_holder_name", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please fill correct card holder name!", nil);
                [self displayMessage:self.LbErName Message:strMessage Value:textfield.text FieldTag:CardName];
                break;
            }
        case CardValidThru: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_correct_expiry_date", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please fill correct expiry date!", nil);
                [self displayMessage:self.LbErValid Message:strMessage Value:textfield.text FieldTag:CardValidThru];
                NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_invalid_expiry_date", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Invalid expiry date!", nil);
                [self invalidValidThruMessage:self.LbErValid Message:strMessage Value:textfield.text FieldTag:CardValidThru];
                break;
            }
        case CardCvv: {
                if(self.cvvFlag) break;
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_correct_cvv_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Please fill correct cvv!", nil);
                [self displayMessage:self.LbErCvv Message:strMessage Value:textfield.text FieldTag:CardCvv];
                NSString *strMsg = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_invalid_cvv_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Invalid cvv number.", nil);
                [self invalidCvvMessage:self.LbErCvv Message:strMsg Value:textfield.text FieldTag:CardCvv];
                break;
            }
        default:
            break;
    }
}

/**
   Display the validation message
*/
- (void) displayMessage: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(cardSuccessFieldNames) fieldTag {
    if ([value isEqualToString:@""]) {
        [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 = @"";
        }
    }
}

/**
   Display the card validation message
*/
- (void) invalidCardMessage: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(cardSuccessFieldNames) fieldTag {
    if (![value isEqualToString:@""]) {
        if (![value isValidCreditCardNumber]) {
            [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 = @"";
            }
        }
    }
}

/**
   Display the validthru validation message
*/
- (void) invalidValidThruMessage: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(cardSuccessFieldNames) fieldTag {
    if (![value isEqualToString:@""]) {
        if (![self validateExpireDate:value]) {
            [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 = @"";
            }
        }
    }
}

/**
  Check the valid thru date
*/
- (bool) validateExpireDate:(NSString*) validThru {
    NSArray *splitArray = [validThru componentsSeparatedByString:@"/"];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger month = [components month]; //current month
    NSInteger year = [components year]; // current year
    NSString *strYear = [@(year) stringValue];
    if([strYear length] == 4) {
        strYear = [strYear substringFromIndex:2];
        year = [strYear intValue];
    }
    NSInteger compareMonth = 12;
    NSInteger compareYear = year + 10;
    if([splitArray count] == 2){
        if([[splitArray objectAtIndex:0] length] == 2 && [[splitArray objectAtIndex:1] length] == 2){//check for 2 digit for month and year
            NSString *m = [splitArray objectAtIndex:0];
            NSString *y = [splitArray objectAtIndex:1];
            if([m doubleValue] > 0 && [m doubleValue] <= compareMonth && [y doubleValue] > 0 && [y doubleValue] <= compareYear){//check for 1-12 month & next ten year
                if([m doubleValue] < month || [y doubleValue] < year){//check for current month and year
                    if([m doubleValue] < month){
                        if([y doubleValue] <= year){
                            return false;
                        } else {
                            return true;
                        }
                    } else {
                        return false;
                    }
                } else {
                   return true;
                }
            } else {
               return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
   Display the cvv validation message
*/
- (void) invalidCvvMessage: (UILabel*) labelName Message:(NSString*)message Value:(NSString*) value FieldTag:(cardSuccessFieldNames) fieldTag {
    if (![value isEqualToString:@""]) {
        if ([value length] < 3) {
            [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 = @"";
            }
        }
    }
}

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

/**
    Update cardsuccess attributes
*/
- (void) updateCardSuccessValues :(UITextField*) textfield {
    switch (textfield.tag) {
        case CardNumber:
            {
                if([textfield.text caseInsensitiveCompare:self.resultCard.extractedCardNumber] != NSOrderedSame) {
                    self.resultCard.cardNumberEditedFlag = true;
                    self.resultCard.editedCardNumber = textfield.text;
                }
                break;
            }
        case CardName:
            {
                if([textfield.text caseInsensitiveCompare:self.resultCard.extractedCardHolderName ] != NSOrderedSame) {
                    self.resultCard.cardHolderNameEditedFlag = true;
                    self.resultCard.editedCardHolderName = textfield.text;
                }
                break;
            }
        case CardValidThru:
            {
                if([textfield.text caseInsensitiveCompare:self.resultCard.extractedDateOfExpire] != NSOrderedSame) {
                    self.resultCard.dateOfExpireEditedFlag = true;
                    self.resultCard.editedDateOfExpire = textfield.text;
                }
                break;
            }
        case CardCvv:
            {
                if([textfield.text caseInsensitiveCompare:self.resultCard.cvv] != NSOrderedSame) {
                    self.resultCard.cvv = textfield.text;
                }
                break;
            }
        default:
            break;
    }
}

/**
    Numeric validation on Textfield
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (!string.length)
        return YES;
    
    if (textField.tag == CardCvv || textField.tag == CardNumber)
    {
        if (textField.tag == CardCvv && textField.text.length > 3)
        return NO;
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
        if (numberOfMatches == 0)
            return NO;
    }
    if(textField.tag == CardValidThru){
        if (textField.text.length > 4)
        return NO;
        if(textField.text.length == 2){
            textField.text = [NSString stringWithFormat:@"%@/",textField.text];
        }
    }
    return YES;
}

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

/** Add toolbar with done button */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    //numberToolbar.barStyle = UIStatusBarStyleLightContent;
    numberToolbar.translucent=NO;
    numberToolbar.barTintColor=[Utilities colorFromColorString:[self.sharedInstance headerColor]];
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(doneButton)];
    [done setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [Utilities colorFromColorString:[self.sharedInstance headerTextColor]],  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)doneButton {
    [self.activeField resignFirstResponder];
    /* for (UITextField* field in self.cardFields) { [field resignFirstResponder]; } */
}

/** 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];
}

/** Adjust the view as per the keyboard appear */
- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSDictionary* info = [aNotification userInfo];
    CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    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)];
       }];
    }
    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 == CardNumber) {
        NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Incorrect card number.", nil);
        [self invalidCardMessage:self.LbErNumber Message:strMessage Value:textField.text FieldTag:CardNumber];
    }
    if (textField.tag == CardValidThru) {
        NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_invalid_expiry_date", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Invalid expiry date!", nil);
        [self invalidValidThruMessage:self.LbErValid Message:strMessage Value:textField.text FieldTag:CardValidThru];
    }
}

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

/**
  Close viewcontroller
*/
-(IBAction) BtClose:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
  Set the extracted values to page
*/
- (void) setValues {
    self.cardImage.image = self.resultCard.cardImage;
    //self.cardImage.layer.cornerRadius = 30;// round the corner of card image
    
    self.cardImage.layer.masksToBounds = YES;
    self.cardImage.layer.cornerRadius = 10.0;
    self.cardImage.layer.borderWidth = 1.0;
    self.cardImage.layer.borderColor = [[UIColor grayColor] CGColor];
    
    for (UITextField* field in self.cardFields) {
        switch (field.tag) {
            case CardNumber:
                {
                    field.text = self.resultCard.extractedCardNumber;
                    NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Incorrect card number", nil);
                    [self invalidCardMessage:self.LbErNumber Message:strMessage Value:field.text FieldTag:CardNumber];
                    break;
                }
            case CardName:
                {
                    field.text = [self.resultCard.extractedCardHolderName capitalizedString];
                    [self showExtractedSuggestedPopup];
                    break;
                }
            case CardValidThru:
                {
                    field.text = self.resultCard.extractedDateOfExpire;
                    break;
                }
            default:
                break;
        }
    }
}

/**
   Check and update the score
*/
- (void) updateScore {
    if(self.resultCard.cardNumberEditedFlag){
        self.resultCard.cardNumberScore = 0;
    } else {
        self.resultCard.cardNumberScore = 100;
    }
}

- (void) callAudit {
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    self.audit_event_Duration = CACurrentMediaTime() - self.audit_event_Duration;
    if(self.audit_event_Duration) {
        NSString *eventDuration = [Utilities stringFromTimeInterval:self.audit_event_Duration];
        NSString *scanDuration = [Utilities stringFromTimeInterval:self.audit_scan_Duration];
        [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 cardSuccessAudit:self.resultCard settings:setting completed:^(NSString *response) {
        NSLog(@"Card success response %@",response);
    } failure:^(NSError *error){
        NSLog(@"Card success response error : %@",error);
    }];
}

/**
  Call the suggestion popup when assign the extracted value
*/
- (void) showExtractedSuggestedPopup {
    bool suggestionFlag = self.sharedInstance.suggestionValidation;
    NSString *accountName = [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]];
    }
    NSString *extractedCardName = self.resultCard.extractedCardHolderName;
    extractedCardName = [extractedCardName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if(suggestionFlag && [accountName length] > 0){
        if(([accountName caseInsensitiveCompare:extractedCardName] != NSOrderedSame)){
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
            VFYSuggestionPopup *vc = [storyboard instantiateViewControllerWithIdentifier:@"VFYSuggestion"];
            vc.popupSelf = (id)self;
            vc.callMethodFlag = CardExtract;
            vc.extCardOwnerName = extractedCardName;
            vc.accOwnerFrstName = self.sharedInstance.accountOwnerFirstName;
            vc.accOwnerLstName = self.sharedInstance.accountOwnerLastName;
            [self presentViewController:vc animated:YES completion:nil];
        }
    }
}

/**
  Call the suggestion popup when submit the form
*/
- (void) showContinueSuggestedPopup {
    bool suggestionFlag = self.sharedInstance.suggestionValidation;
    bool isEditedCardName = self.resultCard.cardHolderNameEditedFlag;
    NSString *accountName = [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]];
    }
    NSString *editedCardName = self.resultCard.editedCardHolderName;
    editedCardName = [editedCardName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *extractedCardName = self.resultCard.extractedCardHolderName;
    if(suggestionFlag && [accountName length] > 0 && isEditedCardName){
        if(([accountName caseInsensitiveCompare:editedCardName] != NSOrderedSame)){
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
            VFYSuggestionPopup *vc = [storyboard instantiateViewControllerWithIdentifier:@"VFYSuggestion"];
            vc.popupSelf = (id)self;
            vc.callMethodFlag = CardContinue;
            vc.extCardOwnerName = extractedCardName;
            vc.accOwnerFrstName = self.sharedInstance.accountOwnerFirstName;
            vc.accOwnerLstName = self.sharedInstance.accountOwnerLastName;
            [self presentViewController:vc animated:YES completion:nil];
        } else {
            [self callCardBack];
        }
    } else {
        [self callCardBack];
    }
}

/**
  Handle the callback from the popup view
*/
- (void) callBackFromPopupClose:(popupCallFromMethod)methodName PassValue:(NSString*)passValue {
    if(methodName == CardExtract){
        if(passValue != nil){
            UITextField* textField = [self.cardFields objectAtIndex:1];
            textField.text = [[passValue valueForKey:@"cardownername"] capitalizedString];
        }
    } else if(methodName == CardContinue){
        if(passValue != nil){
            UITextField* textField = [self.cardFields objectAtIndex:1];
            textField.text = [[passValue valueForKey:@"cardownername"] capitalizedString];
            self.resultCard.editedCardHolderName = textField.text;
        }
        [self callCardBack];
    }
}

- (void) callCardBack {
    [self callAudit];
    [[NSNotificationCenter defaultCenter] postNotificationName:VFY_OBSERVER_CARDSUCCESS object:self.resultCard];
    [self.navigationController popToRootViewControllerAnimated:NO];
}

@end
