//
//  AdViewCustomEventRewarded.m
//  AdViewSDKDemo
//
//  Created by hupan on 2022/3/9.
//  Copyright © 2022 AdView. All rights reserved.
//

#import "AdViewCustomEventRewarded.h"
#import <AdViewSDK/AdViewSDK.h>

@interface AdViewCustomEventRewarded ()<GADMediationAdapter, GADMediationRewardedAd, AdViewVideoDelegate>

@property (nonatomic, strong) AdViewVideo * video;

@property (nonatomic, copy) NSString *appID;

@property (nonatomic, copy) NSString *positionId;

@property (nonatomic, assign) bool isReady;

@property (nonatomic, weak, nullable) id<GADMediationRewardedAdEventDelegate> delegate;

@property (nonatomic, copy, nullable) GADMediationRewardedLoadCompletionHandler completion;

@end

@implementation AdViewCustomEventRewarded

#pragma mark GADMediationAdapter implementation

+ (nullable Class<GADAdNetworkExtras>)networkExtrasClass
{
    return nil;
}

+ (GADVersionNumber)adSDKVersion
{
    NSString *versionString = [AdViewView sdkVersion];
    NSMutableArray *versionComponents = [[NSMutableArray alloc] init];
    for (int i = 0; i < versionString.length; i++) {
        NSRange range;
        range.location = i;
        range.length = 1;
        NSString *str = [versionString substringWithRange:range];
        [versionComponents addObject:str];
    }
    GADVersionNumber version = { 0 };
    if (versionComponents.count == 3) {
        version.majorVersion = [versionComponents[0] integerValue];
        version.minorVersion = [versionComponents[1] integerValue];
        version.patchVersion = [versionComponents[2] integerValue];
    }
    return version;
}

+ (GADVersionNumber)adapterVersion
{
    NSString *versionString = @"1.0.0.0";
    NSArray *versionComponents = [versionString componentsSeparatedByString:@"."];
    GADVersionNumber version = { 0 };
    if (versionComponents.count == 4) {
        version.majorVersion = [versionComponents[0] integerValue];
        version.minorVersion = [versionComponents[1] integerValue];
        version.patchVersion =
            [versionComponents[2] integerValue] * 100 + [versionComponents[3] integerValue];
    }
    return version;
}


- (void)loadRewardedAdForAdConfiguration:(GADMediationRewardedAdConfiguration *)adConfiguration
                       completionHandler:(GADMediationRewardedLoadCompletionHandler)completionHandler
{
    self.completion = completionHandler;
    self.isReady = NO;
    NSString *adUnit = adConfiguration.credentials.settings[@"parameter"];
    if (![self checkAppParameter:adUnit]) {
        return;
    }
    
    self.video = [AdViewVideo playVideoWithAppId:self.appID
                                      positionId:self.positionId
                                       videoType:AdViewVideoTypeInstl delegate:self];
    [self.video setInterfaceOrientations:[UIApplication sharedApplication].statusBarOrientation];
    [self.video getVideoAD];
}

- (BOOL)checkAppParameter:(NSString *)parameter{
    if (parameter && ![parameter isEqualToString:@""]) {
        NSArray *array = [parameter componentsSeparatedByString:@";"];
        self.appID = array.firstObject;
        self.positionId = array.lastObject;
        return YES;
    }
    NSString *errorMessage = @"parameter can not be extracted. Please check your configuration on AdMob dashboard.";
    NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
    NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:userInfo];
    if (self.completion) {
        self.completion(nil, error);
    }
    return NO;
}


#pragma mark GADMediationRewardedAd implementation

- (void)presentFromViewController:(UIViewController *)viewController
{
    if (self.isReady) {
        [self.video showVideoWithController:viewController];
        self.isReady = NO;
    } else {
        NSString *errorMessage = @"The advertisement is not ready, please show it again.";
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : errorMessage };
        NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:0 userInfo:userInfo];
        [self.delegate didFailToPresentWithError:error];
    }
}

#pragma mark AdViewVideoDelegate implementation

- (void)adViewVideoDidReceiveAd:(NSString *)vastString {
    
}

- (void)adViewVideoIsReadyToPlay:(AdViewVideo *)video {
    self.delegate = self.completion(self, nil);
    self.isReady = YES;
}

- (void)adViewVideoFailReceiveDataWithError:(NSError *)error {
    [self.delegate didFailToPresentWithError:error];
}

- (void)adViewVideoPlayStarted {
    [self.delegate willPresentFullScreenView];
    [self.delegate reportImpression];
    [self.delegate didStartVideo];
}

- (void)adViewVideoPlayEnded {
    [self.delegate didEndVideo];

    [self.delegate didRewardUser];
}

- (void)adViewVideoSkipped {
}

- (void)adViewVideoClosed {
    [self.delegate willDismissFullScreenView];
}
- (void)adViewVideoClicked {
    [self.delegate reportClick];
}
- (BOOL)logMode {
    return YES;
}
@end
