//
//  NativeViewController.m
//  AdViewSDKDemo
//
//  Created by unakayou on 11/1/19.
//  Copyright © 2019 AdView. All rights reserved.
//

#import "NativeViewController.h"

@interface NativeViewController () <AdViewNativeAdDelegate>
@property (nonatomic, strong) AdViewNativeAd * native;
@property (nonatomic, strong) UIView * nativeAdView;
@end

@implementation NativeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSizeCtrlView];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    }
}
- (void)requestButtonClick:(UIButton *)sender {
    if (self.nativeAdView) {
        [self.nativeAdView removeFromSuperview];
    }
    self.native = [[AdViewNativeAd alloc] initWithAppKey:ADVIEW_APPID positionID:ADVIEW_POSID_NATIVE];
    self.native.delegate = self;
    self.native.controller = self;
    [self.native loadNativeAdWithCount:1];
}

- (void)closeButtonClick:(UITapGestureRecognizer *)recognizer {
    [self.nativeAdView removeFromSuperview];
    self.nativeAdView = nil;
}

- (void)sliderValueChanged:(UISlider *)slider {
    CGRect nativeAdViewFrame = self.nativeAdView.frame;
    nativeAdViewFrame.size.height *= slider.value;
    if (!CGRectEqualToRect(CGRectZero, nativeAdViewFrame)) self.backgroundScrollView.bounds = nativeAdViewFrame;
    self.percentLabel.text = [NSString stringWithFormat:@"%.f %%", slider.value * 100];
}

- (void)adViewNativeAdSuccessToLoadAd:(AdViewNativeAd *)adViewNativeAd NativeData:(NSArray <AdViewNativeData *>*)nativeDataArray {
    [self makeUpNativeAdViewFromData:nativeDataArray.firstObject];
    [self resetCtrlView];
    [self viewDidLayoutSubviews];
}

- (void)adViewNativeAdFailToLoadAd:(AdViewNativeAd *)adViewNativeAd WithError:(NSError *)error {
    NSLog(@"%s - %@",__FUNCTION__, error.domain);
}

- (void)adViewNativeAdClosed {
    
}

- (void)adViewNativeAdResignActive {
    
}

- (void)adViewNativeAdWillShowPresent {

}

static NSString * optOutCilickURL = nil;
static AdViewNativeData * staticDdata = nil;
- (void)makeUpNativeAdViewFromData:(AdViewNativeData *)data {
    
    staticDdata = data;
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
    __block UIImage *mainImage;
    NSArray * imageArray = [data.adProperties objectForKey:@"imageList"];
    if (imageArray && imageArray.count > 0){
        for (NSString *imageURL in imageArray) {
            if (imageURL != nil) {
                [self loadImageForURLString:imageURL queue:defaultQueue group:group successHandler:^(UIImage *image) {
                    mainImage = image;
                }];
            }
        }
    }else{
        NSString *imageString = [data.adProperties objectForKey:@"imageUrlString"];
        if (imageString != nil) {
            [self loadImageForURLString:imageString queue:defaultQueue group:group successHandler:^(UIImage *image) {
                mainImage = image;
            }];
        }
    }
    
    //App icon
    __block UIImage * iconImg;
    NSString * iconUrlStr = [data.adProperties objectForKey:@"iconUrlString"];
    if (iconUrlStr != nil) {
        [self loadImageForURLString:iconUrlStr queue:defaultQueue group:group successHandler:^(UIImage *image) {
            iconImg = image;
        }];
    }

    __block UIImage * adImg;
    NSString * adUrlStr = [data.adProperties objectForKey:@"adIcon"];
    if (adUrlStr != nil) {
        [self loadImageForURLString:adUrlStr queue:defaultQueue group:group successHandler:^(UIImage *image) {
            adImg = image;
        }];
    }
    
    //App name
    UILabel * titleLabel = [[UILabel alloc] init];
    titleLabel.text = [data.adProperties objectForKey:@"title"];
    
    //App description
    UILabel * descLabel = [[UILabel alloc] init];
    descLabel.text = [data.adProperties objectForKey:@"desc"];
    
    //opt-out
    NSString *optOutIconURL = data.adProperties[@"pimage"];
    optOutCilickURL = data.adProperties[@"pclick"];
    __block UIImage *optOutIconImage;
    if(optOutIconURL != nil){
        [self loadImageForURLString:optOutIconURL queue:defaultQueue group:group successHandler:^(UIImage *image) {
            optOutIconImage = image;
        }];
    }
   
    dispatch_group_notify(group, defaultQueue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImageView *iconImgView;
            if (iconImg == nil) {
                NSLog(@"Error! iconImg is nil");
            }else {
                iconImgView = [[UIImageView alloc] initWithImage:iconImg];
            }
            UIImageView *optOutIcon;
            if (optOutIconImage) {
                optOutIcon =  [[UIImageView alloc] initWithImage:optOutIconImage];
                optOutIcon.userInteractionEnabled = YES;
                UITapGestureRecognizer *optOutIconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(optOutIconClick:)];
                [optOutIcon addGestureRecognizer:optOutIconTap];
            }else{
                NSLog(@"Error! optOutIconImage is nil");
            }
            UIImageView *mainAdImageView;
            if (mainImage) {
                mainAdImageView = [[UIImageView alloc] initWithImage:mainImage];
            }else{
                NSLog(@"Error! mainImage is nil");
            }
            UIImageView *adImgView;
            if (adImg) {
                adImgView = [[UIImageView alloc] initWithImage:adImg];
            }else{
                NSLog(@"Error! adImg is nil");
            }
            self.nativeAdView = [[UIView alloc] init];
            self.nativeAdView.layer.borderWidth = 1.0f;
            self.nativeAdView.userInteractionEnabled = YES;
            NSMutableArray * friendlyObstructionArray = [NSMutableArray new];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(nativeAdClick:)];
            [self.nativeAdView addGestureRecognizer:tap];
            
            [self.nativeAdView addSubview:iconImgView];
            [self.nativeAdView addSubview:titleLabel];
            [self.nativeAdView addSubview:descLabel];
            [self.nativeAdView addSubview:optOutIcon];
            [self.nativeAdView addSubview:mainAdImageView];
            [self.nativeAdView addSubview:adImgView];
            [self.backgroundScrollView addSubview:self.nativeAdView];
            
            for (UIView * view in self.nativeAdView.subviews) {
                [friendlyObstructionArray addObject:view];
            }
            [friendlyObstructionArray addObject:self.nativeAdView];
            
            [self.native showNativeAdWithData:data
                     friendlyObstructionArray:friendlyObstructionArray
                                       onView:self.nativeAdView];
            NSLog(@"Already Displayed");
            CGFloat x = 0, y = 0;
            CGFloat iconLength = 50;
            CGFloat width = self.view.frame.size.width - SPACE * 2;
            CGFloat height = iconLength;
            if (mainAdImageView.frame.size.width) {
                height = iconLength + mainAdImageView.frame.size.height / (mainAdImageView.frame.size.width / width);
            }
            self.nativeAdView.frame = CGRectMake(x, y, width, height);
            self.backgroundScrollView.frame = CGRectMake(SPACE, SPACE, width, height);
            self.backgroundScrollView.contentSize = CGSizeMake(0, height);
            
            iconImgView.frame = CGRectMake(x, y, iconLength, iconLength);
            x += iconImgView.frame.size.width;
            
            titleLabel.frame = CGRectMake(x, y, width - iconImgView.frame.size.width - iconLength, iconImgView.frame.size.height / 2);
            y += titleLabel.frame.size.height;
            
            descLabel.frame = CGRectMake(x, y, titleLabel.frame.size.width, titleLabel.frame.size.height);
            x += descLabel.frame.size.width;
            y += descLabel.frame.size.height;
            
            optOutIcon.frame = CGRectMake(x+15, 0, iconLength-20, iconLength-20);
            x = 0;
            
            mainAdImageView.frame = CGRectMake(x, y, width, height - y);
            adImgView.frame  = CGRectMake(x, height - 10, 10, 10);
            
        });
    });
}


- (void)optOutIconClick:(id)sender {
    
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:optOutCilickURL] options:@{} completionHandler:nil];
    }
}

- (void)nativeAdClick:(UITapGestureRecognizer *)recognizer {
    [self.native clickNativeAdWithData:staticDdata
                        withClickPoint:CGPointMake(50, 50)
                                onView:recognizer.view];
   
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGRect requestButtonFrame = self.requestButton.frame;
        requestButtonFrame.origin.y += SPACE + requestButtonFrame.size.height;
        self.closebutton.frame = requestButtonFrame;

    

}

- (void)loadImageForURLString:(NSString *)urlString queue:(dispatch_queue_t)queue group:(dispatch_group_t)group successHandler:(void (^)(UIImage *image))successHandler;
{
    dispatch_group_async(group, queue, ^{
        dispatch_group_enter(group);
        [[[NSURLSession sharedSession] dataTaskWithURL: [NSURL URLWithString: urlString]
                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
            if ( error )
            {}
            else if ( data )
            {
                UIImage *image = [UIImage imageWithData: data];
                if ( image )
                {
                    successHandler(image);
                }
            }
            dispatch_group_leave(group);
        }] resume];
    });
}

@end
