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

#import <MoPub/MoPub.h>
#import <SmaatoSDKNative/SmaatoSDKNative.h>
#import "SMAMoPubNativeAdapterViewController.h"
#import "SMAMoPubSmaatoNativeAdapter.h"
#import "DemoMoPubNativeAdapterAdView.h"
 
NSString *const MoPubNativeAdsTip_TryLoad = @"Tap ‘Load’ to load a native";
NSString *const MoPubNativeAdsTip_Loading = @"Native is loading…";
NSString *const MoPubNativeAdsTip_Loaded = @"Native was loaded successfully";
NSString *const MoPubNativeAdsTip_Clicked = @"Native has been clicked";
NSString *const MoPubNativeAdsTip_Error = @"Something failed. See console logs";
    
@interface SMAMoPubNativeAdapterViewController () <MPNativeAdDelegate>
@property (nonatomic) MPNativeAd *nativeAd;

@property(nonatomic, weak) IBOutlet AdBlockView *adBlockView;
@property(nonatomic, weak) IBOutlet UILabel *adUnitIDLabel;
@property(nonatomic, weak) IBOutlet UIButton *showButton;
@property(nonatomic, weak) IBOutlet UILabel *adapterVersionLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidLoadLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidFailLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeWillPresentModalViewLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeDidDismissModalViewLabel;
@property(nonatomic, weak) IBOutlet UILabel *nativeWillLeaveAppLabel;

@end

@implementation SMAMoPubNativeAdapterViewController

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

#pragma mark - Actions

- (IBAction)loadButtonTapped:(id)sender
{
    [self resetLabels];
    self.nativeAd = nil;
    self.adBlockView.tip = MoPubNativeAdsTip_Loading;
    self.showButton.enabled = NO;

    // Load new Native ads
    [self loadMopubNativeAdWithAdUnitId:self.mopubModel.adUnitId];
}

- (IBAction)showButtonTapped:(id)sender
{
    self.showButton.enabled = NO;
    [self addNativeViewOnScreen];
}

- (void)setupUI
{
    self.title = @"MoPub Native";
    self.adBlockView.tip = MoPubNativeAdsTip_TryLoad;
    self.adapterVersionLabel.text = [NSString stringWithFormat:@"Adapter version %@", SMAMoPubSmaatoNativeAdapter.version];
    self.adUnitIDLabel.text = self.mopubModel.adUnitId;
}

- (void)resetLabels
{
    self.nativeDidLoadLabel.alpha = 0.2;
    self.nativeDidFailLabel.alpha = 0.2;
    self.nativeWillPresentModalViewLabel.alpha = 0.2;
    self.nativeDidDismissModalViewLabel.alpha = 0.2;
    self.nativeWillLeaveAppLabel.alpha = 0.2;
}

#pragma mark - <MPNativeAdDelegate>

- (void)willPresentModalForNativeAd:(MPNativeAd *)nativeAd
{
    NSLog(@"Mopub Native %@ will present modal view", nativeAd);
    self.nativeWillPresentModalViewLabel.alpha = 1;
}

- (void)didDismissModalForNativeAd:(MPNativeAd *)nativeAd
{
    NSLog(@"Mopub Native %@ did dismiss modal view", nativeAd);
    self.nativeDidDismissModalViewLabel.alpha = 1;
}

- (void)willLeaveApplicationFromNativeAd:(MPNativeAd *)nativeAd
{
    NSLog(@"Mopub Native %@ will leave application", nativeAd);
    self.nativeWillLeaveAppLabel.alpha = 1;
}

- (UIViewController *)viewControllerForPresentingModalView
{
    return self;
}

#pragma mark - Private

- (void)loadMopubNativeAdWithAdUnitId:(NSString *)adUnitId
{
    if (!adUnitId.length) {
        NSLog(@"Expect for valid adUnitId");
        return;
    }

    MPStaticNativeAdRendererSettings *settings = [MPStaticNativeAdRendererSettings new];
    settings.renderingViewClass = [DemoMoPubNativeAdapterAdView class];
    
    MPNativeAdRendererConfiguration *config = [MPStaticNativeAdRenderer rendererConfigurationWithRendererSettings:settings];
    if (!config) {
        NSLog(@"Invalid Mopub config");
        return;
    }
    config.supportedCustomEvents = @[@"SMAMoPubSmaatoNativeAdapter"];
    
    MPNativeAdRequestTargeting *targeting = [MPNativeAdRequestTargeting targeting];
    targeting.desiredAssets = [NSSet setWithObjects:kAdTextKey, kAdTitleKey, kAdMainImageKey, kAdIconImageKey, kAdCTATextKey, kAdStarRatingKey, nil];
    
    MPNativeAdRequest *adRequest = [MPNativeAdRequest requestWithAdUnitIdentifier:adUnitId rendererConfigurations:@[config]];
    adRequest.targeting = targeting;
    
    __typeof__(self) __weak wSelf = self;
    [adRequest startWithCompletionHandler:^(MPNativeAdRequest *request, MPNativeAd *response, NSError *error) {
        __typeof__(self) sSelf = wSelf;
        if (!sSelf) {
            return;
        }
        
        if (response) {
            sSelf.nativeAd = response;
            sSelf.nativeAd.delegate = sSelf;
            [sSelf didSuccess];
        } else {
            [sSelf didFail];
        }
    }];
    
}

- (void)addNativeViewOnScreen
{
    NSError *error = nil;
    UIView *nativeAdView = [self.nativeAd retrieveAdViewWithError:&error];
    
    if (nativeAdView) {
        nativeAdView.frame = self.adBlockView.bounds;
        nativeAdView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self.adBlockView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.adBlockView addSubview:nativeAdView];
    } else {
        NSLog(@"Mopub Native error: %@", error);
        [self didFail];
    }
}

- (void)didFail
{
    self.adBlockView.tip = MoPubNativeAdsTip_Error;
    self.nativeDidFailLabel.alpha = 1;
}

- (void)didSuccess
{
    self.showButton.enabled = YES;
    self.adBlockView.tip = MoPubNativeAdsTip_Loaded;
    self.nativeDidLoadLabel.alpha = 1;
}

@end
