//
//  CDVInAppViewController.m
//  Indigitall
//
//  Created by indigitall on 13/12/23.
//

#import "CDVInAppViewController.h"
#import <Indigitall/INEventUtils.h>
#import <Indigitall/INInAppFormUtils.h>
#import <Indigitall/INInAppAPIConstants.h>
#import <Indigitall/INInAppUtils.h>
@implementation CDVInAppViewController
- (id) initWithContent:(NSString *)content inApp: (INInApp *)inApp closeIcon:(nullable UIButton *)closeIcon closeIconDisabled:(Boolean)closeIconDisabled failed:(void(^)(NSArray<INInAppError*> *error))failed formSubmit:(nullable void(^)(INInApp *inApp, NSDictionary *json))formSubmit{
    @try {
        self = [super init];
        self.inapp = inApp;
        [INEventUtils eventPrintInAppRequest:self.inapp];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didSelect:)];
        [self.view addGestureRecognizer:tap];
        
        if (inApp.properties.layout.borderRadius > 0){
            self.webView.layer.cornerRadius = inApp.properties.layout.borderRadius;
            self.webView.layer.masksToBounds = true;
            self.webView.layer.opaque = false;
        }
        NSString *finalHtml = content;
        [self setConstraints:inApp];

        [self addButtonsWithCloseButton: closeIcon closeIconDisabled: closeIconDisabled];

        NSString *script = INInAppAPIConstants.INAPP_SCRIPT;
        if (inApp.customData != nil) {
            NSMutableDictionary *dicCustomData = [NSMutableDictionary new];
            if ([inApp.customData isKindOfClass:[NSString class]] && ![inApp.customData isEqual: @""]) {
                NSString * stringCustomData = inApp.customData;
                NSData *data = [stringCustomData dataUsingEncoding:NSUTF8StringEncoding];
                id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
                NSLog(@"soy string");
                dicCustomData = json;
            } else {
                dicCustomData = [inApp.customData copy];
            }
            for (int i = 0; i < dicCustomData.count; i++) {
                finalHtml = [finalHtml stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"{{%@}}", [dicCustomData allKeys][i]] withString:[dicCustomData allValues][i]];
            }
        }
        if (failed != nil) self.failed = failed;
        if (formSubmit != nil) self.formSubmit = formSubmit;
        
        NSString *htmlOnSubmit = [INInAppFormUtils editingFormHtml:finalHtml script:script];
        
        [self.webView loadHTMLString:htmlOnSubmit baseURL:nil];

    } @catch (NSException *ex) {
        NSLog(@"PopUp error: %@", ex.description);
    }
    return self;
}

- (void) addButtonsWithCloseButton:(nullable UIButton *)closeIcon closeIconDisabled:(Boolean)closeIconDisabled{
    UIButton *closeButton = [[UIButton alloc]init];
    if (closeIcon != nil){
        closeButton = closeIcon;
    }else{
        closeButton = [[UIButton alloc]initWithFrame: CGRectZero];
        closeButton.backgroundColor = UIColor.grayColor;
        closeButton.layer.cornerRadius = 20;
        closeButton.clipsToBounds = true;
        [closeButton setTitle:@"X" forState:normal];
        [closeButton setTitleColor:UIColor.whiteColor forState:normal];
        closeButton.translatesAutoresizingMaskIntoConstraints = false;
    }
    if (!closeIconDisabled){
        [self.view addSubview:closeButton];
        [closeButton addTarget:self action:@selector(didClose) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self.webView attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
        [self.view addConstraint:[NSLayoutConstraint constraintWithItem:closeButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.webView attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    }
}

- (void) didSelect:(UITapGestureRecognizer *)gestureRecognizer{
    CGPoint location = [gestureRecognizer locationInView:self.webView];
//    NSLog(@"width %f\nheight %f",self.webView.frame.size.width,self.webView.frame.size.height);
    if (location.y >0 && location.x >0 && location.x < self.webView.frame.size.width &&location.y < self.webView.frame.size.height){
        if (self.inapp.properties.numberOfClicks > 0 && self.inapp != nil) [INInAppUtils inAppWasTappedWithInApp:self.inapp];
        if (self.didTouch) self.didTouch();
    }else{
        if (self.didDismissed != nil) self.didDismissed();
    }
    [self dismissViewController];
}

- (void) didClose{
    if (self.didCancel) self.didCancel();
    [self dismissViewController];
}

- (void) dismissViewController{
    [self dismissViewControllerAnimated:true completion:nil];
}


- (void) setConstraints: (INInApp *)inApp{
    //CGFloat aspect = [self getAspectRatioWithWidth:inApp.InAppWidth height:inApp.InAppHeight];
    CGFloat density = [UIScreen mainScreen].scale;
    CGFloat heightDensity = inApp.inAppHeight*density;
    CGFloat widthDensity = inApp.inAppWidth*density;
    CGFloat aspect = [self getAspectRatioWithWidth:widthDensity height:heightDensity];

    NSLayoutConstraint *horizontalConstraint = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
    NSLayoutConstraint *verticalConstraint = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
    
    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:[self pixelToPoints:widthDensity*aspect]];
    
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:self.webView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:[self pixelToPoints:heightDensity*aspect]];

    [self.view addConstraints:@[horizontalConstraint, verticalConstraint,widthConstraint, heightConstraint]];
}

- (CGFloat) getAspectRatioWithWidth: (CGFloat)width height: (CGFloat)height{
    CGFloat screen_width = [UIScreen mainScreen].bounds.size.width;// * 0.90;
    CGFloat screen_height = [UIScreen mainScreen].bounds.size.height ;// * 0.90;
    
    CGFloat aspectWidth = 1.0;
    CGFloat aspectheight = 1.0;
    if (width > screen_width){
        aspectWidth = screen_width/width;
    }
    if (height > screen_height){
        aspectheight = screen_height/height;
    }
    if (aspectheight == aspectWidth){
        return aspectheight;
    }else if (aspectWidth < aspectheight){
        return aspectWidth * 0.9;
    }else{
        return aspectheight * 0.9;
    }
}

- (CGFloat )pixelToPoints:(CGFloat )px{
    CGFloat points = px;
    CGFloat scale_screen = [UIScreen mainScreen].scale;// + 1.0;
    if (scale_screen < 3.0) {
        scale_screen++;
//        points = px/scale_screen;
    }
    return points;
}

@end
