//
//  ViewController.m
//  AdCompDemo
//
//  Created by maming on 15/7/7.
//  Copyright (c) 2015年 maming. All rights reserved.
//

#import "ViewController.h"
#import "AdCompView.h"
#import "AdCompView+Impl.h"
#import "AdCompViewDelegate.h"
#import "AdViewExtTool.h"
#import "AdCompNativeAd.h"

#define NATIVEKEY @"SDK20151311010501u7hth0gexjm9gym"
#define PositionID @"qrak8rs7z7a8"
#define SCREENSIZE ([UIScreen mainScreen].bounds.size)

@interface ViewController () <AdCompViewDelegate,AdCompNativeAdDelegate> {
    UILabel *bannerState;
    UILabel *instlState;
    UILabel *nativeState;
}

@property (strong, nonatomic) AdCompView *banner;
@property (strong, nonatomic) AdCompView *instl;
@property (strong, nonatomic) UILabel *bannerState;
@property (strong, nonatomic) UILabel *instlState;
@property (strong, nonatomic) UILabel *nativeState;

@property (nonatomic, strong) AdCompNativeAd *nativeAd;

@property (nonatomic,strong) NSArray *adArr;
@property (nonatomic,strong) UILabel *label;
//原生广告数据序号
@property (nonatomic,assign) int adCountIndex;

@end

@implementation ViewController
@synthesize banner;
@synthesize bannerState;
@synthesize instl;
@synthesize instlState;
@synthesize nativeState;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat space = 10;
    CGFloat buttonHeight = screenSize.height / 10
    ;
    
    UIButton *bannerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    bannerButton.frame = CGRectMake(space, screenSize.height / 2 - space - buttonHeight, screenSize.width - 2 * space, buttonHeight);
    [bannerButton setTitle:@"请求banner广告" forState:UIControlStateNormal];
    [bannerButton addTarget:self action:@selector(requestAd:) forControlEvents:UIControlEventTouchUpInside];
    bannerButton.tag = 1001;
    bannerButton.backgroundColor = [AdViewExtTool hexStringToColor:BLUE_COLOR];
    bannerButton.tintColor = [UIColor whiteColor];
    bannerButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:bannerButton];
    
    self.bannerState = [[UILabel alloc] initWithFrame:CGRectMake(0, bannerButton.frame.origin.y + 90, screenSize.width, 60)];
    bannerState.text = @"";
    bannerState.textAlignment = NSTextAlignmentCenter;
    bannerState.textColor = [UIColor blackColor];
    [self.view addSubview:bannerState];
    
    UIButton *instlButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    instlButton.frame = CGRectMake(space, screenSize.height / 2 + space, screenSize.width - 2 * space, buttonHeight);
    [instlButton setTitle:@"请求插屏广告" forState:UIControlStateNormal];
    [instlButton addTarget:self action:@selector(requestAd:) forControlEvents:UIControlEventTouchUpInside];
    instlButton.tag = 1002;
    instlButton.backgroundColor = [AdViewExtTool hexStringToColor:RED_COLOR];
    instlButton.tintColor = [UIColor whiteColor];
    instlButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:instlButton];

    self.instlState = [[UILabel alloc] initWithFrame:CGRectMake(0, instlButton.frame.origin.y + 90, screenSize.width, 60)];
    instlState.text = @"";
    instlState.textColor = [UIColor blackColor];
    instlState.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:instlState];
    
    UIButton *nativeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    nativeButton.frame = CGRectMake(space, screenSize.height / 2 + space*2 + buttonHeight, screenSize.width - 2 * space, buttonHeight);
    [nativeButton setTitle:@"请求原生广告" forState:UIControlStateNormal];
    [nativeButton addTarget:self action:@selector(nativeRequest) forControlEvents:UIControlEventTouchUpInside];
    nativeButton.tag = 1003;
    nativeButton.backgroundColor = [AdViewExtTool hexStringToColor:BLUE_COLOR];
    nativeButton.tintColor = [UIColor whiteColor];
    nativeButton.titleLabel.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:nativeButton];
    
    self.nativeState = [[UILabel alloc] initWithFrame:CGRectMake(0, nativeButton.frame.origin.y + 90, screenSize.width, 60)];
    nativeState.text = @"";
    nativeState.textColor = [UIColor blackColor];
    nativeState.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:instlState];
}
- (void)nativeRequest{
    [self closeAd:nil];
    
    self.nativeAd= [[AdCompNativeAd alloc] initWithAppKey:NATIVEKEY positionID:PositionID];
    self.nativeAd.delegate = self;
    self.nativeAd.controller = self;
    [self performSelector:@selector(nativeLoad) withObject:nil afterDelay:1];
    

}

- (void)nativeLoad{
    [self.nativeAd loadNativeAdWithCount:3];
}
- (void)requestAd:(id)sender {
    UIButton *button = (UIButton*)sender;
    if (button.tag == 1001) {
        if (self.banner) {
            [self.banner pauseRequestAd];
            [self.banner removeFromSuperview];
        }
        self.banner = [AdCompView requestWithDelegate:self withAdPlatType:ADCOMPVIEWADPLATTYPE_ADVIEW];
        [self.view addSubview:self.banner];
        self.banner.center = CGPointMake(self.view.frame.size.width / 2.0, 44);
//        self.bannerState.text = @"Banner 请求中。。。";
    }else {
        self.instl = [AdCompView requestAdInstlWithDelegate:self withAdPlatType:ADCOMPVIEWADPLATTYPE_ADVIEW];
//        self.instlState.text = @"Instl 请求中。。。";
    }
}

- (CGSize)changeSize:(CGSize)size from:(CGSize)standardSize {
    CGSize rectSize;
    //    standardSize = CGSizeMake(standardSize.width*0.8, standardSize.width*0.8);
    
    CGFloat scaleX = size.width/standardSize.width;
    CGFloat scaleY = size.height/standardSize.height;
    CGFloat scale = (scaleX > scaleY) ? scaleX : scaleY;
    rectSize = CGSizeMake(size.width / scale, size.height / scale);
    
    return rectSize;
}

- (void)createNativeAdView{
    
    NSLog(@"conut :%lu , index %d",(unsigned long)self.adArr.count,self.adCountIndex);
    
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    dispatch_async(dispatch_get_main_queue(), ^{
        
        for (UIView *view in self.view.subviews) {
            if (view.tag == 1000) {
                [view removeFromSuperview];
            }
        }
        
        if (!self.adArr || self.adArr.count < 1) {
            return ;
        }
        
        AdCompNativeData *info = [self.adArr objectAtIndex:self.adCountIndex];
        
        //      图标
        UIImage *iconImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[info.adProperties objectForKey:@"icon"] objectForKey:@"url"]]]];
        UIImageView *iconImgView = [[UIImageView alloc] initWithImage:iconImage];
        BOOL isOverLength = NO;
        if (iconImage) {
            if (iconImage.size.width / iconImage.size.height > 3) {
                isOverLength = YES;
                CGSize size = [self changeSize:iconImage.size from:SCREENSIZE];
                iconImgView.frame = CGRectMake(0, 0, size.width, size.height);
            }else
                iconImgView.frame = CGRectMake(0, 0, 60 * iconImage.size.width / iconImage.size.height, 60);
        }
        
        CGFloat showSizeW = isOverLength ? iconImgView.frame.size.width:SCREENSIZE.width;
        
        //      图片
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[info.adProperties objectForKey:@"images"] firstObject] objectForKey:@"url"]]]];
        UIImageView *imgView = [[UIImageView alloc] initWithImage:image];
        if (image) {
            imgView.frame = CGRectMake(0, iconImgView.frame.size.height, showSizeW, showSizeW* image.size.height/image.size.width);
        }
        
        CGFloat showSizeH = iconImgView.frame.size.height + imgView.frame.size.height;
        
        UIView *showView = [[UIView alloc] initWithFrame:CGRectMake((SCREENSIZE.width-showSizeW)/2, 64, showSizeW, showSizeH)];
        showView.backgroundColor = [UIColor clearColor];
        showView.tag = 1000;
        
        if (!isOverLength) {
            CGFloat space = 10;
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(space + iconImgView.frame.size.width, 0, SCREENSIZE.width - space - iconImgView.frame.size.width, 30)];
            title.text = [info.adProperties objectForKey:@"title"];
            
            UILabel *des = [[UILabel alloc] initWithFrame:CGRectMake(space + iconImgView.frame.size.width, title.frame.size.height, SCREENSIZE.width - space - iconImgView.frame.size.width, 30)];
            des.text = [info.adProperties objectForKey:@"desc"];
            des.numberOfLines = 0;
            [showView addSubview:title];
            [showView addSubview:des];
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click)];
        [showView addGestureRecognizer:tap];
        [showView addSubview:iconImgView];
        [showView addSubview:imgView];
        [self.view addSubview:showView];
        
        [self.nativeAd showNativeAdWithData:info onView:showView];
    });
    
}
- (IBAction)closeAd:(id)sender {
    for (UIView *view in self.view.subviews) {
        if (view.tag == 1000) {
            [view removeFromSuperview];
        }
        self.nativeAd.delegate = nil;
        self.nativeAd = nil;
        self.adArr = nil;
    }
}

- (void)click{
    [self.nativeAd clickNativeAdWithData:[self.adArr objectAtIndex:self.adCountIndex] withClickPoint:CGPointMake(100, 100)];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - AdCompViewDelegate
-(NSString*) appId {
    return @"SDK20111022530129m85is43b70r4iyc";
}

- (UIViewController*)viewControllerForShowModal {
    return self;
}

-(void) didReceivedAd:(AdCompView *)adView reuse:(BOOL)isReuse {
    NSLog(@"didReceivedAd:reuse:");
    if (self.banner) {
        CGFloat fWidth = self.view.frame.size.width;
        CGRect frm = adView.frame;
        frm.origin.x = (fWidth - frm.size.width) / 2;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 7) {
            frm.origin.y = 20;
        }
        adView.frame = frm;
    }
    if (self.instl.isReady) {
        [self.instl showWithRootViewController:self];
    }
//    if (adView == self.banner) {
//        self.bannerState.text = @"banner 请求成功";
//    }else
//        self.instlState.text = @"instl 请求成功";
}

-(void)didFailToReceiveAd:(AdCompView*)adView Error:(NSError*)error {
    NSLog(@"didFailToReceiveAd:%@",error);
    NSString *errStr = [NSString stringWithFormat:@"didFailToReceiveAd, For:%@",
                        [error description]];
//    if (adView == self.banner) {
//        self.bannerState.text = [NSString stringWithFormat:@"banner 失败：%@",errStr];
//    }else
//        self.instlState.text = [NSString stringWithFormat:@"instl 失败：%@",errStr];
}

- (void)adViewWillPresentScreen:(AdCompView *)adView {
    NSLog(@"adViewWillPresentScreen");
}

- (void)adViewDidDismissScreen:(AdCompView *)adView {
    NSLog(@"adViewDidDismissScreen");
}

- (void)adInstlDidDismissScreen:(AdCompView *)adInstl
{
    
}
- (BOOL)logMode
{
    return YES;
}
- (BOOL)testMode{
    return NO;
}
#pragma mark nativeAd delegate
- (void)adCompNativeAdSuccessToLoadNativeData:(NSArray*)nativeDataArray{
    self.adArr = nativeDataArray;
    self.adCountIndex = 0;
    self.label.text = @"请求广告成功";
    [self createNativeAdView];
}

- (void)adCompNativeAdFailToLoadWithError:(NSError*)error {
    NSLog(@"%@",error.domain);
}

- (void)adCompNativeAdWillShowPresent {
    NSLog(@"native ad will show present");
}

- (void)adCompNativeAdClosed {
    NSLog(@"native ad did closed");
}

- (void)adCompNativeAdResignActive {
    NSLog(@"app resign active");
}

@end
