//
//  VFYFrontGuideWrapper.m
//  Verif-y
//
//  Created by MTN on 13/09/20.
//

#import "VFYFrontGuideWrapper.h"
#import "VFYFailImagePreviewWrapper.h"
#import "VFYVerifyApp.h"
#import "VFYFailFinalPreviewWrapper.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <QuartzCore/QuartzCore.h>
#import "VFYButton.h"
#import "VFYConstant.h"
#import "VFYAuditManager.h"

@interface VFYFrontGuideWrapper ()

@property (weak, nonatomic) IBOutlet UILabel *LbFrontSide;
@property (weak, nonatomic) IBOutlet UILabel *LbFrontInstruction;
@property (weak, nonatomic) IBOutlet VFYButton *LbBtContinue;
@property (weak, nonatomic) IBOutlet UILabel *LbFrontStep;
@property (weak, nonatomic) IBOutlet UILabel *LbStepMsg;
@property (weak, nonatomic) IBOutlet UIImageView *GuideImage;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoPow;
@property (weak, nonatomic) IBOutlet UILabel *LbLogoBy;
@property (weak, nonatomic) IBOutlet UIScrollView *BodyScrollView;
@property (nonatomic, retain) VFYVerifyApp *sharedInstance;
@property (nonatomic) CFTimeInterval elapsedTime;
@property (nonatomic, strong) NSBundle *bundlePath;

@end

@implementation VFYFrontGuideWrapper

@synthesize selectionType;
@synthesize stepType;

- (void)viewDidLoad {
    [super viewDidLoad];
    if (@available(iOS 13.0, *)) {
         self.view.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    self.sharedInstance = [VFYVerifyApp sharedInstance];
    self.bundlePath = [NSBundle bundleForClass:[VFYVerifyApp class]];
    if([self.stepType isEqualToString:@"first"]){
        NSString *msg = [NSString string];
        if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_PASSPORT] == NSOrderedSame ) {
            self.GuideImage.image = [UIImage imageNamed:@"vfypassport.png"];
           self.GuideImage.contentMode = UIViewContentModeScaleAspectFill;
           msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_6", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Front of passport", nil);
       } else {
           self.GuideImage.image = [UIImage imageNamed:@"vfy-id-front.png"];
           self.GuideImage.contentMode = UIViewContentModeCenter;
           if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_IDENTITY] == NSOrderedSame ) {
               msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_8", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Front of identity card", nil);
           } else {
               msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_2", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Front of driver's license", nil);
           }
       }
       self.LbFrontSide.text = msg;
       self.LbFrontInstruction.text = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_center_id", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Center ID", nil);
       self.LbFrontStep.text = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_take_photo", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Take photo", nil);
    } else if([self.stepType isEqualToString:@"second"]){
       NSString *msg = [NSString string];
       if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_PASSPORT] == NSOrderedSame ) {
           self.GuideImage.image = [UIImage imageNamed:@"vfypassport.png"];
           self.GuideImage.contentMode = UIViewContentModeScaleAspectFill;
           msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_7", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Back of passport", nil);
       } else {
           self.GuideImage.image = [UIImage imageNamed:@"vfy-id-back.png"];
           self.GuideImage.contentMode = UIViewContentModeCenter;
           if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_IDENTITY] == NSOrderedSame ) {
               msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_9", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Back of identity card", nil);
           } else {
               msg = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_userguidance_msg_3", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Back of diver's license", nil);
           }
       }
       self.LbFrontSide.text = msg;
       self.LbFrontInstruction.text = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_turn_over_id", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Turn over ID", nil);
       self.LbFrontStep.text = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_turn_over_id", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Turn over ID", nil);
    }
    self.LbStepMsg.text = NSLocalizedStringWithDefaultValue(@"mb_identityFailed_clear_details_msg", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Make sure details are clear", nil);
    [self.LbBtContinue setTitle:NSLocalizedStringWithDefaultValue(@"mb_identity_button_1", [self.sharedInstance language], [self.sharedInstance languageBundlePath], @"Continue", nil) forState:UIControlStateNormal];
    [self CustomTitle];
    [self.BodyScrollView setBackgroundColor:[Utilities colorFromColorString:self.sharedInstance.bodyColor]];
    /*self.GuideImage.layer.borderColor = [UIColor blackColor].CGColor;
    self.GuideImage.layer.borderWidth = 2.0;
    self.GuideImage.layer.cornerRadius = 2.0;
    [self.GuideImage setClipsToBounds:YES];*/
    [self setBrandingColor];
}

- (void) setBrandingColor {
    [self.LbLogoPow setTextColor:[Utilities colorFromColorString:VFY_LOGO_POWER]];
    [self.LbLogoBy setTextColor:[Utilities colorFromColorString:VFY_LOGO_BY]];
    /* Set button style */
    [self.LbBtContinue animateOnPress:FALSE borderColor:[Utilities colorFromColorString:[self.sharedInstance buttonBorderColor]] backGroundColor:[Utilities colorFromColorString:[self.sharedInstance buttonBackgroundColor]] textColor:[Utilities colorFromColorString:[self.sharedInstance buttonTextColor]]];
}

- (IBAction)BTNContinue:(id)sender {
    if(self.selectionType){
        [self openCameraView];
    } else {
        [self openImagePickerView];
    }
}

- (void) openImagePickerView {
    UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void) openCameraView {
    UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void) openImagePreviewController:(UIImage *) image {
    if([self.stepType isEqualToString:@"first"]){
        if(self.selectionType){
            /** For passport there will be no back scan */
            if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_PASSPORT] == NSOrderedSame ) {
                NSString *base64String = [Utilities encodeToBase64String:image];
                self.idFail.frontimage = base64String;
                //Delay is call to fix blank screen issue
                double delayInSeconds = 0.5;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self callAudit];
                    [[NSNotificationCenter defaultCenter] postNotificationName:VFY_OBSERVER_IDFAIL object:self.idFail];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            } else {
                NSString *base64String = [Utilities encodeToBase64String:image];
                self.idFail.frontimage = base64String;
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
                VFYFrontGuideWrapper *newView = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFRONTGUIDE_STORYBOARD];
                newView.selectionType = self.selectionType;
                newView.stepType = @"second";
                newView.idFail = self.idFail;
                newView.idFailDurationStart = self.idFailDurationStart;
                [self.navigationController pushViewController:newView animated:YES];
            }
        } else {
            /** For passport there will be no back scan */
            if( [self.idFail.documenttype caseInsensitiveCompare:VFY_DOCUMENTTYPE_PASSPORT] == NSOrderedSame ) {
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
                VFYFailFinalPreviewWrapper *newView = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFAILFINAL_STORYBOARD];
                newView.selectionType = self.selectionType;
                newView.passImage = image;
                newView.idFail = self.idFail;
                newView.idFailDurationStart = self.idFailDurationStart;
                [self.navigationController pushViewController:newView animated:YES];
            } else {
                UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
                VFYFailImagePreviewWrapper *newView = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFAILPREVIEW_STORYBOARD];
                newView.selectionType = self.selectionType;
                newView.passImage = image;
                newView.idFail = self.idFail;
                newView.idFailDurationStart = self.idFailDurationStart;
                [self.navigationController pushViewController:newView animated:YES];
            }
        }
    } else if([self.stepType isEqualToString:@"second"]){
        if(self.selectionType){
            NSString *base64String = [Utilities encodeToBase64String:image];
            self.idFail.backimage = base64String;
            //Delay is call to fix blank screen issue
            double delayInSeconds = 0.5;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self callAudit];
                [[NSNotificationCenter defaultCenter] postNotificationName:VFY_OBSERVER_IDFAIL object:self.idFail];
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        } else {
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:VFY_MAIN_STORYBOARD bundle:self.bundlePath];
            VFYFailFinalPreviewWrapper *newView = [storyboard instantiateViewControllerWithIdentifier:VFY_IDFAILFINAL_STORYBOARD];
            newView.selectionType = self.selectionType;
            newView.passImage = image;
            newView.idFail = self.idFail;
            [self.navigationController pushViewController:newView animated:YES];
        }
    } else {
        NSLog(@"FrontGuide no steptype");
    }
}

-(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];
    }
}

- (void) callAudit {
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    self.elapsedTime = CACurrentMediaTime() - self.idFailDurationStart;
    if(self.elapsedTime) {
        NSString *duration = [Utilities stringFromTimeInterval:self.elapsedTime];
        [setting setValue:duration forKey:@"audit_event_duration"];
    } else {
        [setting setValue:@"" forKey:@"audit_event_duration"];
    }
    [VFYAuditManager idFailAudit:self.idFail settings:setting completed:^(NSString *response) {
        NSLog(@"Id fail response %@",response);
    } failure:^(NSError *error){
        NSLog(@"Id fail response error : %@",error);
    }];
}

#pragma mark UIImagePickerControllerDelegate
 
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString* mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if (CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
        UIImage* picture = nil;//[info objectForKey:UIImagePickerControllerEditedImage];
        if (!picture){
            picture = [info objectForKey:UIImagePickerControllerOriginalImage];
            [self openImagePreviewController:picture];
        }
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
