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

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

@interface VFYCardReviewWrapper()
{

}

/** IBoutlet for branding */
@property (weak, nonatomic) IBOutlet UILabel *LbLogoPow;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoBy;
@property (weak, nonatomic) IBOutlet VFYButton *btnContinue;
@property (weak, nonatomic) IBOutlet VFYButton *btnTryAgain;
@property (weak, nonatomic) IBOutlet VFYButton *btnContinueSuccess;
@property (weak, nonatomic) IBOutlet UIView *successBtnContainer;
/** Miscellaneous variable*/
@property (nonatomic) BOOL cvvFlag;
@property (nonatomic) BOOL cardImageFlag;
@property (nonatomic, strong) NSMutableArray *failedValidateCount;
/** IBoutlet for extra varibles */
@property (nonatomic, strong) NSArray *validThruMonth;
@property (nonatomic, strong) NSArray *validThruYear;
@property (nonatomic, strong) NSString *selectMonth;
@property (nonatomic, strong) NSString *selectYear;
@property (nonatomic, retain) VFYVerifyApp *sharedInstance;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/** Error label */
@property (weak, nonatomic) IBOutlet UILabel *lblErrCardNumber;
@property (weak, nonatomic) IBOutlet UILabel *lblErrCardName;
@property (weak, nonatomic) IBOutlet UILabel *lblErrValidThru;
@property (weak, nonatomic) IBOutlet UIImageView *successImage;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYCardReviewWrapper


- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 13.0, *)) {
         self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    self.lblErrValidThru.text = @"";
    self.lblErrCardNumber.text = @"";
    self.lblErrCardName.text = @"";
    self.successImage.image = nil;
    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 setValues];
}

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


/** Add localization text on labels */
- (void) setLocalizationText {
    [self.btnContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_card_scan_button", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Continue", nil) forState:UIControlStateNormal];
    [self.btnTryAgain setTitle:NSLocalizedStringWithDefaultValue(@"mb_cardFailed_try_again_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:false borderColor:[Utilities colorFromColorString:[self.sharedInstance buttonBorderColor]] backGroundColor:[Utilities colorFromColorString:[self.sharedInstance buttonBackgroundColor]] textColor:[Utilities colorFromColorString:[self.sharedInstance buttonTextColor]]];
    [self.btnTryAgain animateOnPress:false borderColor:[Utilities colorFromColorString:[self.sharedInstance buttonBorderColor]] backGroundColor:[Utilities colorFromColorString:[self.sharedInstance buttonBackgroundColor]] textColor:[Utilities colorFromColorString:[self.sharedInstance buttonTextColor]]];
    [self.btnContinueSuccess animateOnPress:false 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;
}

/**
  Continue button
*/
- (IBAction)btnContinue:(id)sender {
    [self callCardBack];
}

- (IBAction)btnTrayAgain:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)btnContinueSuccess:(id)sender {
    [self callCardBack];
}

/** Validation check method */
- (void)validationCheck {
    self.failedValidateCount = [NSMutableArray new];
    for (int i=1081; i < 1084; i++) {
        [self emptyTextfieldValidation:i];
    }
}

/**
 Validation as per the textfields
*/
- (void) emptyTextfieldValidation :(int) fieldName {
    NSString *strMessage = [NSString string];
    switch (fieldName) {
        case CardNumber: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_empty_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Card number is empty!", nil);
                [self displayMessage:self.lblErrCardNumber Message:strMessage Value:self.resultCard.extractedCardNumber FieldTag:CardNumber];
                NSString *strMsg = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_card_number", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Incorrect card number", nil);
                [self invalidCardMessage:self.lblErrCardNumber Message:strMsg Value:self.resultCard.extractedCardNumber FieldTag:CardNumber];
                break;
            }
        case CardName: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_empty_card_holder_name", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Card holder name is empty!", nil);
                [self displayMessage:self.lblErrCardName Message:strMessage Value:self.resultCard.extractedCardHolderName FieldTag:CardName];
                [self showExtractedSuggestedPopup];
                break;
            }
        case CardValidThru: {
                strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_empty_expiry_date", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Expiry date is empty!", nil);
                [self displayMessage:self.lblErrValidThru Message:strMessage Value:self.resultCard.extractedDateOfExpire FieldTag:CardValidThru];
                NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_incorrect_invalid_expiry_date", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Invalid expiry date!", nil);
                [self invalidValidThruMessage:self.lblErrValidThru Message:strMessage Value:self.resultCard.extractedDateOfExpire FieldTag:CardValidThru];
                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 = @"";
            }
        }
    }
}

/**
  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 {
    if ([self.resultCard.extractedCardNumber isEqualToString:@""] && [self.resultCard.extractedDateOfExpire isEqualToString:@""] && [self.resultCard.extractedCardHolderName isEqualToString:@""]) {
        NSString *strMessage = NSLocalizedStringWithDefaultValue(@"mb_valdiationCard_empty_fields", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"This document is not supported. Please try again.", nil);
        [self displayMessage:self.lblErrCardNumber Message:strMessage Value:@"" FieldTag:CardNumber];
    } else {
        [self validationCheck];
        if([self.failedValidateCount count] == 0){
            self.successImage.image = [UIImage imageNamed:@"vfy-review-success.png"];
            self.successBtnContainer.hidden = false;
            self.btnContinue.hidden = true;
            self.btnTryAgain.hidden = true;
        }
    }
}

- (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){
            self.resultCard.editedCardHolderName = [[passValue valueForKey:@"cardownername"] capitalizedString];
            self.lblErrCardName.text = @"";
            if([self.lblErrCardNumber.text length] == 0 && [self.lblErrValidThru.text length] == 0){
                self.successImage.image = [UIImage imageNamed:@"vfy-review-success.png"];
                self.successBtnContainer.hidden = false;
                self.btnContinue.hidden = true;
                self.btnTryAgain.hidden = true;
            }
        }
    }
}

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

@end
