#import "InAppNativeViewController.h"
#import "AdViewDemoMacros.h"

NSString * const nativeStoredImpressionInApp = @"POSID06zhclyweype";

@interface InAppNativeViewController ()

@property (nonatomic) ADVIEW_NativeAd * nativeAd;
@property (nonatomic) ADVIEW_NativeRequest * nativeUnit;

@end

@implementation InAppNativeViewController

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

- (void)loadView {
    [super loadView];
}

- (void)createAd {
    self.nativeUnit = [[ADVIEW_NativeRequest alloc] initWithConfigId:nativeStoredImpressionInApp];

    self.nativeUnit.context = ADVIEW_ContextType.Social;
    self.nativeUnit.placementType = ADVIEW_PlacementType.FeedContent;
    self.nativeUnit.contextSubType = ADVIEW_ContextSubType.Social;

    @weakify(self);
    [self.nativeUnit fetchDemandWithCompletionBidInfo:^(ADVIEW_BidInfo * _Nonnull bidInfo) {
        @strongify(self);
        if (!self) { return; }

        NSDictionary * targetingKeywords = bidInfo.targetingKeywords ?: @{};
        NSString * cacheId = [targetingKeywords valueForKey:@"hb_cache_id_local"];

        ADVIEW_NativeAd * nativeAd = [ADVIEW_NativeAd createWithCacheId:cacheId];

        if (nativeAd == nil) {
            return;
        }

        self.nativeAd = nativeAd;

        self.titleLable.text = self.nativeAd.title;
        self.bodyLabel.text = self.nativeAd.text;
        [self updateCallToActionButtonTitle:self.nativeAd.callToAction];
        self.sponsoredLabel.text = self.nativeAd.sponsoredBy;

        [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:self.nativeAd.iconUrl] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.iconView.image = [[UIImage alloc] initWithData:data];
            });
        }] resume];

        [[NSURLSession.sharedSession dataTaskWithURL:[NSURL URLWithString:self.nativeAd.imageUrl] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                self.mainImageView.image = [[UIImage alloc] initWithData:data];
            });
        }] resume];

        [self.nativeAd registerViewWithView:self.view clickableViews:@[self.callToActionButton, self.mainImageView, self.iconView]];
    }];
}

@end
