//
//  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)requestButtonClick:(UIButton *)sender {
    [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];
}

- (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;
    
    //App icon
    NSString * iconUrlStr = [data.adProperties objectForKey:@"iconUrlString"];
    UIImage * iconImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:iconUrlStr]]];
    UIImageView * iconImgView = [[UIImageView alloc] initWithImage:iconImage];
    if (iconImage == nil) {
        NSLog(@"Error! iconImage is nil"); return;
    }

    //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"];
    UIImage *optOutIconImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:optOutIconURL]]];
    UIImageView *optOutIcon = [[UIImageView alloc] initWithImage:optOutIconImage];
    optOutIcon.userInteractionEnabled = YES;
    UITapGestureRecognizer *optOutIconTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(optOutIconClick:)];
    [optOutIcon addGestureRecognizer:optOutIconTap];
    if (optOutIconImage) {
        if (optOutIconImage == nil) {
            NSLog(@"Error! optOutIconImage is nil"); return;
        }
    }

    //image
    UIImage *mainImage = nil;
    NSArray * imageArray = [data.adProperties objectForKey:@"imageList"];
    if (imageArray && imageArray.count) {
        mainImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageArray[0]]]];
    } else {
        NSString *imageString = [data.adProperties objectForKey:@"imageUrlString"];
        mainImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageString]]];
    }
    if (mainImage == nil) {
        NSLog(@"Error! mainImage is nil"); return;
    }
    
    UIImageView * mainAdImageView = [[UIImageView alloc] initWithImage:mainImage];
    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.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 + mainImage.size.height / (mainImage.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, 0, iconLength, iconLength);
    x = 0;

    mainAdImageView.frame = CGRectMake(x, y, width, height - y);
}

- (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 contentFrame = self.backgroundScrollView.frame;
    if (self.nativeAdView) {
        contentFrame.origin.x = (self.view.frame.size.width - self.nativeAdView.frame.size.width) / 2;
    }
    contentFrame.origin.y = SPACE + 80;
    self.backgroundScrollView.frame = contentFrame;
    self.backgroundScrollView.contentSize = CGSizeMake(0, self.nativeAdView.frame.size.height);
    
    CGRect requestButtonFrame = self.requestButton.frame;
    requestButtonFrame.origin.y += SPACE + requestButtonFrame.size.height;
    self.closebutton.frame = requestButtonFrame;
}

@end
