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

#import "VFYCardGuideWrapper.h"
#import "VFYCardSuccessWrapper.h"
#import "Utilities.h"
#import "VFYButton.h"
#import "VFYConstant.h"
#import "ResultModelCard.h"
#import "VFYCardSuccessWrapper.h"
#import "VFYCardFailWrapper.h"
#import "VFYCardReviewWrapper.h"

#import <MicroBlink/MicroBlink.h>
//#import <BlinkCard/BlinkCard.h>

@interface VFYCardGuideWrapper() <MBBlinkCardOverlayViewControllerDelegate>//<MBBlinkCardOverlayViewControllerDelegate>
{

}

@property (nonatomic, nonnull) MBBlinkCardRecognizer *blinkCardRecognizer;

@property (nonatomic, strong) NSString *licenseErrorMessage;

@property (weak, nonatomic) IBOutlet UILabel *CardTitle;
@property (weak, nonatomic) IBOutlet UILabel *CardInstruction;
@property (weak, nonatomic) IBOutlet VFYButton *BTNContinue;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoPow;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoBy;
@property (weak, nonatomic) IBOutlet UIScrollView *BodyScrollView;
@property (weak, nonatomic) IBOutlet UINavigationItem *navigation;
@property (weak, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (strong, nonatomic) NSTimer *t;
@property (nonatomic) CFTimeInterval audit_event_Duration;
@property (nonatomic) CFTimeInterval audit_scan_Duration;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYCardGuideWrapper

@synthesize audit_event_Duration, audit_scan_Duration;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (@available(iOS 13.0, *)) {
        self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cardSuccessCallFromNthChild:) name:VFY_OBSERVER_CARDSUCCESS object:nil];
    self.sharedInstance = [VFYVerifyApp sharedInstance];
    [self setLocalizationText];
    [self CustomTitle];
    [self setBrandingColor];
    [self setCloseButton];
    
    audit_event_Duration = CACurrentMediaTime();
}

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

/**
 Receive method use to handle call from nth child
 */
- (void) cardSuccessCallFromNthChild:(NSNotification *)notify {
    if(notify.object != nil){
      ResultModelCard *vfyCardSuccess = (ResultModelCard*)notify.object;
      [self.cardGuide callClose:CardSuccessComplete PassValue:vfyCardSuccess];
    } else {
      [self.cardGuide callClose:CardSuccessClose];
    }
}

/**
   Set border on rotation of device
*/
- (void) viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    if (@available(iOS 13.0, *)) {
        /* Uncomment below to add background color in statusbar **/
        /* UIView *statusBar = [[UIView alloc]initWithFrame:[UIApplication sharedApplication].keyWindow.windowScene.statusBarManager.statusBarFrame] ;
        statusBar.backgroundColor = [UIColor blackColor];
        [[UIApplication sharedApplication].keyWindow addSubview:statusBar]; */
    }
}

/**
  Add localization text on labels
*/
- (void) setLocalizationText {
  /* self.CardTitle.text = NSLocalizedStringWithDefaultValue(@"mb_card_userguidance_title", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"अपनी आईडी तैयार रखें!", nil);
   self.CardInstruction.text = NSLocalizedStringWithDefaultValue(@"mb_card_userguidance_subtitle", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"एक मान्य क्रेडिट / डेबिट कार्ड का उपयोग करें", nil);
   [self.BTNContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_card_button_1", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"जारी रखें", nil) forState:UIControlStateNormal];*/
   self.CardTitle.text = NSLocalizedStringWithDefaultValue(@"mb_card_get_your_card_ready", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Get Your Card Ready!", nil);
   self.CardInstruction.text = NSLocalizedStringWithDefaultValue(@"mb_card_valid_card", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Use a valid Credit/Debit card", 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 shadow
    [self.navigationBar.layer setShadowColor: [Utilities colorFromColorString:VFY_NAVIGATION_BODER].CGColor];
    [self.navigationBar.layer setShadowOffset: CGSizeMake(0, 2)];
    [self.navigationBar.layer setShadowRadius:1.0];
    [self.navigationBar.layer setShadowOpacity: 0.7]; */
    [[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.BodyScrollView 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]]];
}

/**
  Continue button to start scanning
*/
- (IBAction)BTNContinue:(id)sender {
    
    audit_scan_Duration = CACurrentMediaTime();
    /*UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:nil];
    VFYCardSuccessWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_CARDSUCCESS_STORYBOARD];
    ResultModelCard *cardResult = [[ResultModelCard alloc] init];
    vc.resultCard = cardResult;
    [self.navigationController pushViewController:vc animated:YES];*/
    [self CallCardScanner];
    //[self callCardFail];
}

/**
  Set all the require setting for camera view
*/
- (void) CallCardScanner {
  self.blinkCardRecognizer = [[MBBlinkCardRecognizer alloc] init];
    self.blinkCardRecognizer.returnFullDocumentImage = YES;
    self.blinkCardRecognizer.extractCvv = false;
    self.blinkCardRecognizer.extractIban = false;
    //set the language
    [[MBMicroblinkApp instance] setLanguage:[self.sharedInstance language]];
    
    MBRecognizerCollection *recognizerCollection = [[MBRecognizerCollection alloc] initWithRecognizers:@[self.blinkCardRecognizer]];
  MBBlinkCardOverlaySettings *overlaySettings = [[MBBlinkCardOverlaySettings alloc] init];
    overlaySettings.enableEditScreen = false;
    
  MBBlinkCardOverlayViewController *blinkCardOveralyViewController = [[MBBlinkCardOverlayViewController alloc] initWithSettings:overlaySettings recognizerCollection:recognizerCollection delegate:self];
    
    UIViewController<MBRecognizerRunnerViewController>* recognizerRunnerViewController = [MBViewControllerFactory recognizerRunnerViewControllerWithOverlayViewController:blinkCardOveralyViewController];
    recognizerRunnerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    /* Timer is start to close the scanner after 22 sec */
    self.t = [NSTimer scheduledTimerWithTimeInterval: 22.0 target: self selector:@selector(callCardFail) userInfo: nil repeats:NO];
    [self presentViewController:recognizerRunnerViewController animated:YES completion:nil];
}

/**
   Scanning get finished
*/
- (void)blinkCardOverlayViewControllerDidFinishScanning:(nonnull MBBlinkCardOverlayViewController *)blinkCardOverlayViewController state:(MBRecognizerResultState)state {
    [blinkCardOverlayViewController.recognizerRunnerViewController pauseScanning];
    if (self.blinkCardRecognizer.result.resultState == MBRecognizerResultStateValid) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [blinkCardOverlayViewController dismissViewControllerAnimated:YES completion:nil];
            [self setCardModel:self.blinkCardRecognizer];
        });
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            //Stop both trace in case of card scan fail
            
            [self.t invalidate]; //stop the timer on scanning get failed.
            [blinkCardOverlayViewController dismissViewControllerAnimated:YES completion:nil];
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
            VFYCardFailWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_CARDFAIL_STORYBOARD];
            [self.navigationController pushViewController:vc animated:YES];
        });
    }
}

/**
   Scanning get cancel
*/
- (void)blinkCardOverlayViewControllerDidTapClose:(nonnull MBBlinkCardOverlayViewController *)blinkCardOverlayViewController {
    [self.t invalidate]; //stop the timer on scanner cancel.
    
    [blinkCardOverlayViewController dismissViewControllerAnimated:YES completion:nil];
}


/**
  Load the cardfail viewcontroller
*/
- (void) callCardFail {
    [self dismissViewControllerAnimated:YES completion:nil];
    //Stop both trace in case of card scan fail
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
    VFYCardFailWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_CARDFAIL_STORYBOARD];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
  Set card model with extracted scanned information
*/
- (void) setCardModel: (MBBlinkCardRecognizer * _Nonnull)creditCard {
    [self.t invalidate]; //stop the timer on scanning get success.
    ResultModelCard *cardResult = [[ResultModelCard alloc] init];
    cardResult.isSuccessful = true;
    cardResult.extractedCardHolderName = creditCard.result.owner;
    cardResult.extractedCardNumber = creditCard.result.cardNumber;
    if(creditCard.result.expiryDate.month != 0 && creditCard.result.expiryDate.year != 0){
        NSInteger intMonth = creditCard.result.expiryDate.month;
        NSString *month = [@(creditCard.result.expiryDate.month) stringValue];
        NSString *year = [@(creditCard.result.expiryDate.year) stringValue];
        if([year length] == 4) {
            year = [year substringFromIndex:2];
        }
        if(intMonth > 0 && intMonth < 10) {
            cardResult.extractedDateOfExpire = [NSString stringWithFormat:@"0%@/%@",month,year];
        } else {
            cardResult.extractedDateOfExpire = [NSString stringWithFormat:@"%@/%@",month,year];
        }
    }
    if(creditCard.result.firstSideFullDocumentImage.image != nil){ cardResult.cardImage = creditCard.result.firstSideFullDocumentImage.image; }
    
    
    if([self.sharedInstance reviewPage]){
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
        VFYCardReviewWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_CARDREVIEW_STORYBOARD];
        vc.resultCard = cardResult;
        vc.audit_scan_Duration = CACurrentMediaTime() - audit_scan_Duration;
        vc.audit_event_Duration = audit_event_Duration;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
        VFYCardSuccessWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_CARDSUCCESS_STORYBOARD];
        vc.resultCard = cardResult;
        vc.audit_scan_Duration = CACurrentMediaTime() - audit_scan_Duration;
        vc.audit_event_Duration = audit_event_Duration;
        if(self.sendMoney){
            vc.sendMoney = self.sendMoney;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/**
  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 button action
*/
-(IBAction) BtClose:(id)sender {
    //[self dismissViewControllerAnimated:YES completion:nil];
    
    [self.t invalidate];
    [self.cardGuide callClose:CardSuccessClose];
}

@end
