//
//  VerifyTest.m
//  Verif-y
//
//  Created by MTN on 02/09/20.
//

#import "VFYIDGuideWrapper.h"
#import "VFYIDSuccessWrapper.h"
#import "VFYIDFailGuideWrapper.h"
#import "Utilities.h"
#import "VFYButton.h"
#import "VFYConstant.h"

#import "VFYIdReviewWrapper.h"
#import <MicroBlink/MicroBlink.h>

@interface VFYIDGuideWrapper() <MBBlinkIdOverlayViewControllerDelegate>
{
    CLLocationManager *locationManager;
    CLGeocoder *geocoder;
    CLPlacemark *placemark;
}

@property (nonatomic, nonnull) MBBlinkIdCombinedRecognizer *blinkIdRecognizer;

@property (weak, nonatomic) IBOutlet UILabel *IDTitle;
//@property (weak, nonatomic) IBOutlet UITextView *IDInstruction;
@property (weak, nonatomic) IBOutlet UILabel *IDInstruction;
@property (weak, nonatomic) IBOutlet VFYButton *BTNContinue;
@property (weak, nonatomic) IBOutlet UINavigationItem *navigation;
@property (weak, nonatomic) IBOutlet UINavigationBar *navigationBar;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoPow;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoBy;
@property (weak, nonatomic) IBOutlet UIScrollView *BodyScrollView;
@property (nonatomic) CFTimeInterval auditEventDuration;
@property (nonatomic) CFTimeInterval auditScanDuration;
@property (strong, nonatomic) NSTimer *scanTimer;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYIDGuideWrapper

@synthesize IDTitle;
@synthesize IDInstruction;
@synthesize BTNContinue;
@synthesize sharedInstance;
@synthesize callDirectlyFlag;

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 13.0, *)) {
         self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    [self setLocalizationText];
    [self CustomTitle];
    [self setBrandingColor];
    [self setCloseButton];
    if([sharedInstance geoLanguage]){
        [self getLocation];
    }
    self.auditEventDuration = CACurrentMediaTime();
     
}

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

/**
  Add localization text on labels
*/
- (void) setLocalizationText {
    self.IDTitle.text = NSLocalizedStringWithDefaultValue(@"mb_identity_userguidance_title", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Get Your ID Ready!", nil);
    self.IDInstruction.text = NSLocalizedStringWithDefaultValue(@"mb_identity_userguidance_subtitle", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Use a valid government-issued photo ID", nil);
    [self.BTNContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_identity_button_1", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Continue", nil) forState:UIControlStateNormal];
}

/**
  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]; */
    /* 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.view setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    [self.BodyScrollView setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    [self.IDTitle 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]]];
}

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

/**
  Continue button redirect it to microblinklink
*/
- (IBAction)btnContinue:(id)sender {
    //[self.idGuide callFrom:@"idguide"];
    //[self successCase:nil];
    //[self failedCase:InDirectly];
    //return;
  
    //Start of scan duration
    
    [[MBMicroblinkApp instance] setLanguage:[self.sharedInstance language]];
    self.auditScanDuration = CACurrentMediaTime();
    self.blinkIdRecognizer = [[MBBlinkIdCombinedRecognizer alloc] init];
    self.blinkIdRecognizer.returnFaceImage = true;
    self.blinkIdRecognizer.returnFullDocumentImage = true;
    MBBlinkIdOverlaySettings *settings = [[MBBlinkIdOverlaySettings alloc] init];
    MBRecognizerCollection *recognizerCollection = [[MBRecognizerCollection alloc] initWithRecognizers:@[self.blinkIdRecognizer]];
    MBBlinkIdOverlayViewController *blinkIdOverlayViewController = [[MBBlinkIdOverlayViewController alloc] initWithSettings:settings recognizerCollection:recognizerCollection delegate:self];
    UIViewController<MBRecognizerRunnerViewController>* recognizerRunnerViewController = [MBViewControllerFactory recognizerRunnerViewControllerWithOverlayViewController:blinkIdOverlayViewController];
    
    [recognizerRunnerViewController setModalPresentationStyle:UIModalPresentationOverFullScreen];
    CATransition *transition = [CATransition animation];
    transition.duration = 0.35;
    transition.timingFunction =
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionMoveIn;
    transition.subtype = kCATransitionFromRight;
    // NSLog(@"%s: self.view.window=%@", _func_, self.view.window);
    UIView *containerView = self.view.window;
    [containerView.layer addAnimation:transition forKey:nil];
    /* Timer is start to close the scanner after 22 sec */
    self.scanTimer = [NSTimer scheduledTimerWithTimeInterval: 22.0 target: self selector:@selector(callIdFail) userInfo: nil repeats:NO];
    [self presentViewController:recognizerRunnerViewController animated:NO completion:nil];
}

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

/**
  Close button
*/
- (IBAction)btnClose:(id)sender {
    
    [self.scanTimer invalidate]; //stop the timer on scanning get success.
    [self.idGuide callClose:IDGuideWrapper];
}

- (void) successCase:(MBBlinkIdCombinedRecognizer *) recognizer {
    
    if([self.sharedInstance reviewPage]){
        self.auditScanDuration = CACurrentMediaTime() - self.auditScanDuration;
        //Stop the scan duration trace
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
        VFYIdReviewWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_IDSUCCESS_REVIEW_STORYBOARD];
        vc.idGuide = self.idGuide;
        vc.sharedInstance = self.sharedInstance;
        vc.recognizerCollection = recognizer;
        vc.callDirectlyFlag = self.callDirectlyFlag;
        //vc.idTrace = self.event_Duration;
        vc.auditScanDuration = self.auditScanDuration;
        vc.auditEventDuration = self.auditEventDuration;
        if(self.sendMoney){
            vc.sendMoney = self.sendMoney;
            //vc.sendmoney_event_Duration = self.sendmoney_event_Duration;
        }
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        self.auditScanDuration = CACurrentMediaTime() - self.auditScanDuration;
        //Stop the scan duration trace
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
        VFYIDSuccessWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_IDSUCCESS_STORYBOARD];
        vc.idGuide = self.idGuide;
        vc.sharedInstance = self.sharedInstance;
        vc.recognizerCollection = recognizer;
        vc.callDirectlyFlag = self.callDirectlyFlag;
        
        vc.auditScanDuration = self.auditScanDuration;
        vc.auditEventDuration = self.auditEventDuration;
        if(self.sendMoney){
            vc.sendMoney = self.sendMoney;
        }
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void) failedCase:(componentCallDirectly)callFlag {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
    VFYIDFailGuideWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFAILGUIDE_STORYBOARD];
    vc.idGuide = self.idGuide;
    vc.callDirectlyFlag = callFlag;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
  Load the cardfail viewcontroller
*/
- (void) callIdFail {
    [self dismissViewControllerAnimated:YES completion:nil];
    [self failedCase:InDirectly];
    //Stop both scan/event duration trace
    /*
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:nil];
    VFYIDFailGuideWrapper *vc = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFAILGUIDE_STORYBOARD];
    vc.idGuide = self.idGuide;
    vc.callDirectlyFlag = InDirectly;
    [self.navigationController pushViewController:vc animated:YES];*/
}

#pragma mark - IdScanDelegate

- (void)blinkIdOverlayViewControllerDidFinishScanning:(MBBlinkIdOverlayViewController *)blinkIdOverlayViewController state:(MBRecognizerResultState)state {
    // check for valid state
    if (state  == MBRecognizerResultStateValid) {
        [blinkIdOverlayViewController.recognizerRunnerViewController pauseScanning];
        dispatch_async(dispatch_get_main_queue(), ^{
            // All UI interaction needs to be done on main thread
            [self.scanTimer invalidate]; //stop the timer on scanning get success.
            [self dismissViewControllerAnimated:YES completion:nil];
            [self successCase:self.blinkIdRecognizer];
        });
    }  else {
        [blinkIdOverlayViewController.recognizerRunnerViewController pauseScanning];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.scanTimer invalidate]; //stop the timer on scanning get success.
            
            [self dismissViewControllerAnimated:YES completion:nil];
            [self failedCase:InDirectly];
        });
      }
}

- (void)blinkIdOverlayViewControllerDidTapClose:(nonnull MBBlinkIdOverlayViewController *)blinkIdOverlayViewController {
    [self.scanTimer invalidate]; //stop the timer on scanning get success.
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - CLLocationManagerDelegate

- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"didFailWithError: %@", error);
}

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations.lastObject;
    [locationManager stopUpdatingLocation];// Stop Location Manager
    // Reverse Geocoding
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
        if (error == nil && [placemarks count] > 0) {
            self->placemark = [placemarks lastObject];
            NSLog(@"%@", self->placemark.country);
            [self showAlertForLanguageChange:self->placemark.country];
        } else {
            NSLog(@"geocoder error %@", error.debugDescription);
        }
    } ];
}

/**
  Message to change the language as per the current geo location
*/
- (void) showAlertForLanguageChange:(NSString*) countryName {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Language Change" message:@"Did you want to change language as per current location" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            [self setGeoLanguage:countryName];
                        }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

/**
  Set the language as per the geo location
*/
- (void) setGeoLanguage:(NSString*) countryName {
    NSString *language;
    language = [Utilities getGeoLanguage:countryName];
    [sharedInstance setLanguage:language];
    [self setLocalizationText];
}

/**
  Location access permission
*/
- (void) getLocation
{
    locationManager = [[CLLocationManager alloc] init];
    geocoder = [[CLGeocoder alloc] init];
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusDenied:
            [self showAlert:@"Location Access Disabled" Message:@"In order to change the language, please open this app's settings and set location access to 'While Using'."];
            break;
        case kCLAuthorizationStatusRestricted:
            [self showAlert:@"Access to Location Services is Restricted" Message:@"limiting your access to language change using location services."];
            break;
        case kCLAuthorizationStatusNotDetermined:
            [locationManager requestWhenInUseAuthorization];
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            break;
    }
    [locationManager setDelegate:self];
    [locationManager startUpdatingLocation];
}

/**
  Show message in case access is rejected for location
*/
- (void) showAlert:(NSString*) title Message:(NSString*) message {
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

@end
