#import "MAXNativeViewController.h"
#import "NativeBaseViewController.h"
#import "AdViewDemoMacros.h"

NSString * const nativeStoredImpressionMAX = @"POSID06zhclyweype";
NSString * const maxRenderingNativeAdUnitId = @"c7e82db66cc5ce85";

@interface MAXNativeViewController ()

@property (nonatomic) ADVIEW_MediationNativeAdUnit * maxMediationNativeAdUnit;
@property (nonatomic) AdViewMAXMediationNativeUtils * mediationDelegate;
@property (nonatomic) MANativeAdLoader * maxNativeAdLoader;
@property (nonatomic, weak) MAAd * maxLoadedNativeAd;
@property (nonatomic, copy) NSArray<NSLayoutConstraint *> * nativeAdPlacementConstraints;

@end

@implementation MAXNativeViewController

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

- (void)dealloc {
    if (self.maxLoadedNativeAd != nil) {
        [self.maxNativeAdLoader destroyAd:self.maxLoadedNativeAd];
    }
}

- (void)applyFeedLayoutToNativeAdView:(MANativeAdView *)nativeAdView {
    UIImageView *iconView = (UIImageView *)[nativeAdView viewWithTag:1];
    UILabel *titleLabel = (UILabel *)[nativeAdView viewWithTag:2];
    UILabel *bodyLabel = (UILabel *)[nativeAdView viewWithTag:3];
    UILabel *sponsoredLabel = (UILabel *)[nativeAdView viewWithTag:4];
    UIButton *callToActionButton = (UIButton *)[nativeAdView viewWithTag:5];
    UIView *mainImageView = [nativeAdView viewWithTag:123];

    if (iconView == nil || titleLabel == nil || bodyLabel == nil || sponsoredLabel == nil || callToActionButton == nil || mainImageView == nil) {
        return;
    }

    [NativeBaseViewController applyFeedLayoutToContainer:nativeAdView
                                                iconView:iconView
                                              titleLabel:titleLabel
                                               bodyLabel:bodyLabel
                                          sponsoredLabel:sponsoredLabel
                                           mainImageView:mainImageView
                                        callToActionButton:callToActionButton
                                         useSafeAreaInsets:NO];
}

- (void)createAd {
    self.maxNativeAdLoader = [[MANativeAdLoader alloc] initWithAdUnitIdentifier:maxRenderingNativeAdUnitId];
    self.maxNativeAdLoader.nativeAdDelegate = self;

    self.mediationDelegate = [[AdViewMAXMediationNativeUtils alloc] initWithNativeAdLoader:self.maxNativeAdLoader];

    self.maxMediationNativeAdUnit = [[ADVIEW_MediationNativeAdUnit alloc] initWithConfigId:nativeStoredImpressionMAX mediationDelegate:self.mediationDelegate];

    [self.maxMediationNativeAdUnit setContextType:ADVIEW_ContextType.Social];
    [self.maxMediationNativeAdUnit setPlacementType:ADVIEW_PlacementType.FeedContent];
    [self.maxMediationNativeAdUnit setContextSubType:ADVIEW_ContextSubType.Social];

    UINib * nativeAdViewNib = [UINib nibWithNibName:@"MAXNativeAdView" bundle:NSBundle.mainBundle];
    MANativeAdView * maNativeAdView = [nativeAdViewNib instantiateWithOwner:nil options:nil].firstObject;

    MANativeAdViewBinder * adViewBinder = [[MANativeAdViewBinder alloc] initWithBuilderBlock:^(MANativeAdViewBinderBuilder * _Nonnull builder) {
        builder.iconImageViewTag = 1;
        builder.titleLabelTag = 2;
        builder.bodyLabelTag = 3;
        builder.advertiserLabelTag = 4;
        builder.callToActionButtonTag = 5;
        builder.mediaContentViewTag = 123;
    }];

    [maNativeAdView bindViewsWithAdViewBinder:adViewBinder];

    @weakify(self);
    [self.maxMediationNativeAdUnit fetchDemandWithCompletion:^(enum ADVIEW_ResultCode resultCode) {
        @strongify(self);
        if (!self) { return; }

        [self.maxNativeAdLoader loadAdIntoAdView:maNativeAdView];
    }];
}

- (void)styleCallToActionButtonInNativeAdView:(MANativeAdView *)nativeAdView {
    UIButton *callToActionButton = (UIButton *)[nativeAdView viewWithTag:5];
    if (callToActionButton == nil) {
        return;
    }

    NSString *rawTitle = callToActionButton.configuration.title ?: [callToActionButton titleForState:UIControlStateNormal];
    UIButtonConfiguration *buttonConfig = callToActionButton.configuration ?: [UIButtonConfiguration filledButtonConfiguration];
    buttonConfig.title = [NativeBaseViewController displayCallToAction:rawTitle];
    buttonConfig.baseBackgroundColor = UIColor.systemBlueColor;
    buttonConfig.baseForegroundColor = UIColor.whiteColor;
    buttonConfig.cornerStyle = UIButtonConfigurationCornerStyleMedium;
    buttonConfig.contentInsets = NSDirectionalEdgeInsetsMake(12, 16, 12, 16);
    callToActionButton.configuration = buttonConfig;
}

- (void)didLoadNativeAd:(MANativeAdView *)nativeAdView forAd:(MAAd *)ad {
    if (self.maxLoadedNativeAd != nil) {
        [self.maxNativeAdLoader destroyAd:self.maxLoadedNativeAd];
    }

    self.maxLoadedNativeAd = ad;

    if (nativeAdView == nil) {
        return;
    }

    [self applyFeedLayoutToNativeAdView:nativeAdView];
    [self styleCallToActionButtonInNativeAdView:nativeAdView];

    self.bannerView.hidden = YES;
    nativeAdView.translatesAutoresizingMaskIntoConstraints = NO;
    if (nativeAdView.superview != self.view) {
        [nativeAdView removeFromSuperview];
        [self.view addSubview:nativeAdView];
    }

    if (self.nativeAdPlacementConstraints.count == 0) {
        self.nativeAdPlacementConstraints = @[
            [nativeAdView.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor constant:15],
            [nativeAdView.leadingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.leadingAnchor constant:15],
            [nativeAdView.trailingAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.trailingAnchor constant:-15]
        ];
        [NSLayoutConstraint activateConstraints:self.nativeAdPlacementConstraints];
    }
}

- (void)didFailToLoadNativeAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error {
    AdViewDemoLogError(@"%@", error.message);
}

- (void)didClickNativeAd:(MAAd *)ad {
}

@end
