//
//  SMANativeViewController.m
//  sdk-demo-ios-objc
//
//  Created by Smaato Inc on 16.04.20.
//  Copyright © 2020 Smaato Inc. All rights reserved.
//

#import "SMANativeViewController.h"
#import "NativeAdCustomView.h"
#import "NativeAdSmaatoView.h"
#import "UIView+DemoNib.h"

NSString *const NativeAdsTip_TryLoad = @"Tap ‘Load’ to load Native";
NSString *const NativeAdsTip_Loading = @"Native loading…";
NSString *const NativeAdsTip_Loaded = @"Native was loaded successfully";
NSString *const NativeAdsTip_Clicked = @"Native has been clicked";
NSString *const NativeAdsTip_Error = @"Something failed. See console logs";

@interface SMANativeViewController () <SMANativeAdDelegate>

@property(nonatomic, weak) IBOutlet UIButton *buttonShow;
@property(nonatomic, weak) IBOutlet UILabel *publisherIdLabel;
@property(nonatomic, weak) IBOutlet UILabel *adspaceIdLabel;
@property(nonatomic, weak) IBOutlet UIScrollView *scrollView;
@property(nonatomic, weak) IBOutlet AdBlockView *adBlock;
@property(nonatomic, weak) IBOutlet UISwitch *switchShowImmediately;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidLoadLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidFailLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeWillPresentModalContentLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidPresentModalContentLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidDismissModalContentLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidClickLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidTTLExpireLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeWillLeaveAppLabel;

@property(nonatomic) SMANativeAd *nativeAd;
@property(nonatomic) UIView *nativeView;

@end

@implementation SMANativeViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
}

#pragma mark - Actions

- (IBAction)btnLoadTapped:(UIButton *)sender
{
    [self resetLabels];
    
    // Remove native view from the screen if it exists
    [self.nativeView removeFromSuperview];
    self.nativeAd = nil;
    
    self.adBlock.tip = NativeAdsTip_Loading;
    self.buttonShow.enabled = NO;
    
    // Load new Native ads
    self.nativeAd = [self loadNativeAdWithAdspaceId:self.adSpaceId];
}

- (IBAction)btnShowTapped:(UIButton *)sender
{
    self.buttonShow.enabled = NO;
    [self addNativeViewOnScreen:self.nativeView];
}

- (void)setupUI
{
    self.adBlock.tip = NativeAdsTip_TryLoad;
    self.publisherIdLabel.text = SmaatoSDK.publisherId;
    self.adspaceIdLabel.text = self.adSpaceId;
    
    switch (self.renderingMode) {
        case SmaatoNativeRenderingManualByPublisher:
            self.switchShowImmediately.enabled = YES;
            break;
            
        case SmaatoNativeRenderingAutoBySDK:
            self.switchShowImmediately.enabled = NO;
            break;
    }

    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)resetLabels
{
    self.nativeDidLoadLabel.alpha = 0.2;
    self.nativeDidFailLabel.alpha = 0.2;
    self.nativeWillPresentModalContentLabel.alpha = 0.2;
    self.nativeDidPresentModalContentLabel.alpha = 0.2;
    self.nativeDidDismissModalContentLabel.alpha = 0.2;
    self.nativeDidClickLabel.alpha = 0.2;
    self.nativeDidTTLExpireLabel.alpha = 0.2;
    self.nativeWillLeaveAppLabel.alpha = 0.2;
}

#pragma mark - <SMANativeAdDelegate>
#pragma mark - Required methods

- (void)nativeAd:(SMANativeAd *)nativeAd didLoadWithAdRenderer:(SMANativeAdRenderer *)renderer {
    NSLog(@"Native loaded successfully %@", nativeAd);
    self.nativeDidLoadLabel.alpha = 1;
    self.adBlock.tip = NativeAdsTip_Loaded;
    
    switch (self.renderingMode) {
        case SmaatoNativeRenderingManualByPublisher:
            self.nativeView = [self doManualRendering:renderer];
            if (self.switchShowImmediately.isOn) {
                [self addNativeViewOnScreen:self.nativeView];
            }
            break;
        case SmaatoNativeRenderingAutoBySDK:
            self.nativeView = [self doAutoRendering:renderer];
            break;
    }
}

- (void)nativeAd:(SMANativeAd *)nativeAd didFailWithError:(NSError *)error {
    NSLog(@"Native %@ failed with error: %@", nativeAd, error);
    self.nativeDidFailLabel.alpha = 1;
    self.adBlock.tip = NativeAdsTip_Error;
}

- (void)nativeAdDidTTLExpire:(SMANativeAd *)nativeAd {
    NSLog(@"Native TTL has expired and you can not use this Native from now. Please load new one. Tip: show Native before expiration for the best fill rate (you have about 5 minutes after loading completion) %@", nativeAd);
    self.nativeDidTTLExpireLabel.alpha = 1;
}

- (UIViewController *)presentingViewControllerForNativeAd:(SMANativeAd *)nativeAd {
    return self;
}

#pragma mark - Optional methods

- (void)nativeAdDidClick:(SMANativeAd *)nativeAd {
    NSLog(@"Native has been clicked %@", nativeAd);
    self.nativeDidClickLabel.alpha = 1;
    self.adBlock.tip = NativeAdsTip_Clicked;
}

- (void)nativeAdWillPresentModalContent:(SMANativeAd *)nativeAd {
    NSLog(@"Native will present a modal content %@", nativeAd);
    self.nativeWillPresentModalContentLabel.alpha = 1;
}

- (void)nativeAdDidPresentModalContent:(SMANativeAd *)nativeAd {
    NSLog(@"Native did present a modal content %@", nativeAd);
    self.nativeDidPresentModalContentLabel.alpha = 1;
}

- (void)nativeAdDidDismissModalContent:(SMANativeAd *)nativeAd {
    NSLog(@"Native did dissmiss a modal content %@", nativeAd);
    self.nativeDidDismissModalContentLabel.alpha = 1;
}

- (void)nativeAdWillLeaveApplicationFromAd:(SMANativeAd *)nativeAd {
    NSLog(@"Native has been clicked %@", nativeAd);
    self.nativeWillLeaveAppLabel.alpha = 1;
}

#pragma mark - Private

- (SMANativeAd *)loadNativeAdWithAdspaceId:(NSString *)adSpaceId {
    if (!adSpaceId.length) {
        NSLog(@"Expect for valid adspaceId");
        return nil;
    }
    
    SMANativeAd *nativeAd = [SMANativeAd new];
    SMANativeAdRequest *adRequest = [[SMANativeAdRequest alloc] initWithAdSpaceId:adSpaceId];
    adRequest.allowMultipleImages = NO;
    adRequest.returnUrlsForImageAssets = NO;
    nativeAd.delegate = self;
    [nativeAd loadWithAdRequest:adRequest];
    
    return nativeAd;
}

- (void)addNativeViewOnScreen:(UIView *)adView {
    self.adBlock.tip = nil;
    if (!self.nativeAd || !adView) {
        NSLog(@"Native ads has not been loaded yet");
        return;
    }
           
    adView.frame = self.adBlock.bounds;
    adView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.adBlock addSubview:adView];
}

- (UIView*)doManualRendering:(SMANativeAdRenderer *)renderer {
    NativeAdCustomView *adView = [NativeAdCustomView demo_instantiateFromNib];
    if (!adView) {
        return nil;
    }
    
    [renderer registerViewForImpression:adView];
    [renderer registerViewsForClickAction:@[adView.titleTextLabel, adView.mainTextLabel, adView.mainImageView, adView.iconImageView, adView.ctaLabel]];

    SMANativeAdAssets *assets = renderer.nativeAssets;
    adView.titleTextLabel.text = assets.title;
    adView.mainTextLabel.text = assets.mainText;
    adView.sponsoredLabel.text = assets.sponsored;

    if (assets.icon.image) {
       adView.iconImageView.image = assets.icon.image;
    } else {
        NSLog(@"Icon image has not been downloaded. Probably you have set `returnUrlsForImageAssets` property of `SMANativeAdRequest` object to `true` or URL link was broken");
    }
    
    if (assets.images.firstObject.image) {
        adView.mainImageView.image = assets.images.firstObject.image;
    } else {
        NSLog(@"Main image has not been downloaded. Probably you have set `returnUrlsForImageAssets` property of `SMANativeAdRequest` object to `true` or URL link was broken");
    }

    self.buttonShow.enabled = YES;
    return adView;
}
    
- (UIView*)doAutoRendering:(SMANativeAdRenderer *)renderer {
    NativeAdSmaatoView *adView = [NativeAdSmaatoView demo_instantiateFromNib];
    if (!adView || ! [adView conformsToProtocol:@protocol(SMANativeView)]) {
        return nil;
    }
    
    __typeof__(self) __weak wSelf = self;
    [renderer renderAdInView:adView completion:^(BOOL isRendered, NSError *error) {
        __typeof__(self) sSelf = wSelf;
        if (!sSelf) {
            return;
        }
        
        if (isRendered) {
            NSLog(@"Native ad has been rendered");
            [renderer registerViewForImpression:adView];
            [renderer registerViewsForClickAction:@[adView.smaTitleLabel, adView.smaMainTextLabel, adView.smaIconView, adView.smaMediaView, adView.smaCTALabel]];
            sSelf.buttonShow.enabled = YES;
        } else {
            NSLog(@"Native ad rendering error %@", error);
        }
    }];
    
    return adView;
}

@end
