//
//  WallPapaerADManager.m
//  HD wallpaper
//
//  Created by aaa on 2024/7/3.
//

#import "WallPapaerADManager.h"
#import <AppLovinSDK/AppLovinSDK.h>

@interface WallPapaerADManager()<MAAdDelegate>
@property (nonatomic,strong) MAAppOpenAd *openAD;
@property (nonatomic,strong) MAInterstitialAd *interstitialAD_Back;
@property (nonatomic,strong) MAInterstitialAd *interstitialAD_Save;
@property (nonatomic,strong) MAInterstitialAd *interstitialAD_Search;
@property (nonatomic,strong) ALSdkInitializationConfiguration *adConfig;

@property (nonatomic) NSInteger retryAttempt_OpenAD;
@property (nonatomic) NSInteger retryAttempt_backAD;
@property (nonatomic) NSInteger retryAttempt_saveAD;
@property (nonatomic) NSInteger retryAttempt_searchAD;

@property (nonatomic,strong) NSTimer *openADTimer;
@property (nonatomic,strong) UIProgressView *processView;
@end

//
#define  kAppLovinSDK_Key @"EG89nBMcGXrN1_U_svJiPhCMTsVu7TEkWvOGtVJUbh4x1Ds9cKJy8pzKr6LXKL7zQXbN3PLy4Q6MRl3oT3lgbX"

#define kWallPaper_OpenAD @"228275830e494edc" //开屏
#define kInterstitial_BackAD @"43c096614eb15e06"//返回 插页
#define kInterstitial_SaveAD @"99a545c14fe760b4" //保存 插页
#define kInterstitial_SearchAD @"fcfba91be4420a25" //搜索 插页
#define kOpenAdCTimeLength 15.0//最多等待开屏广告加载时常
#define kOpenADPerSec 0.05
@implementation WallPapaerADManager
//配置广告
- (void)configureAD{
    
    _adConfig = [ALSdkInitializationConfiguration configurationWithSdkKey: kAppLovinSDK_Key builderBlock:^(ALSdkInitializationConfigurationBuilder *builder) {
            builder.mediationProvider = ALMediationProviderMAX;
            NSString *currentIDFV = UIDevice.currentDevice.identifierForVendor.UUIDString;
            if ( currentIDFV.length > 0 )
            {
                builder.testDeviceAdvertisingIdentifiers = @[currentIDFV];
            }
      }];

      // Initialize the SDK with the configuration
      [[ALSdk shared] initializeWithConfiguration: _adConfig completionHandler:^(ALSdkConfiguration *sdkConfig) {
        // Start loading ads
          NSLog(@"zzh  ....sdkconfig:\n%@",sdkConfig);
          
          [[WallPapaerADManager shareInstance] initOpenAD];
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              [[WallPapaerADManager shareInstance] initIntersitialAD];
          });
      }];
}

+ (instancetype)shareInstance {
    static WallPapaerADManager * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [WallPapaerADManager new];
    });
    return instance;
}

- (id)init {
    self = [super init];
    if(self){
        
    }
    return self;
}


- (void)initOpenAD{
    self.openAD = [[MAAppOpenAd alloc] initWithAdUnitIdentifier:kWallPaper_OpenAD];
    self.openAD.delegate = self;
    [self.openAD loadAd];
}

//初始化插页广告
- (void)initIntersitialAD {
    self.interstitialAD_Back = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: kInterstitial_BackAD];
    self.interstitialAD_Back.delegate = self;
    [self.interstitialAD_Back loadAd];
    
    self.interstitialAD_Save = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: kInterstitial_SaveAD];
    self.interstitialAD_Save.delegate = self;
    [self.interstitialAD_Save loadAd];
    
    self.interstitialAD_Search = [[MAInterstitialAd alloc] initWithAdUnitIdentifier: kInterstitial_SearchAD];
    self.interstitialAD_Search.delegate = self;
    [self.interstitialAD_Search loadAd];
}

- (void)showIntersitialAD_Back:(WallPapaerADManagerCallback)callback {
    self.callback = callback;
    if ( [self.interstitialAD_Back isReady] ){
      [self.interstitialAD_Back showAd];
    }
    else {
        self.callback(1);
    }
}


- (void)showIntersitialAD_Save:(WallPapaerADManagerCallback)callback {
    self.callback = callback;
    if ( [self.interstitialAD_Save isReady] ){
      [self.interstitialAD_Save showAd];
    }
    else {
        self.callback(1);
    }
}

- (void)showIntersitialAD_Search:(WallPapaerADManagerCallback)callback {
    self.callback = callback;
    if ( [self.interstitialAD_Search isReady] ){
      [self.interstitialAD_Search showAd];
    }
    else {
        self.callback(1);
    }
}

- (void)checkOpenADReadyState{
    static CGFloat totalTimeC = 0.0;
    totalTimeC += kOpenADPerSec;
    
    if ( [self.openAD isReady] ){
        [_openADTimer invalidate];
        _openADTimer = nil;
        [self.openAD showAd];
    }
    else {
        if (totalTimeC > kOpenAdCTimeLength) {//超时
            NSLog(@"超时关闭等待开屏广告页...");
            if(self.callback) {
                self.callback(1);
            }
            [_openADTimer invalidate];
            _openADTimer = nil;
        }
        else {
            CGFloat v = totalTimeC / kOpenAdCTimeLength;
            _processView.progress = v;
        }
    }
}

- (void)showFirstOpenAD:(WallPapaerADManagerCallback)callback window:(UIWindow *)window {
    
    self.callback = callback;
    
    if ( ![[ALSdk shared] isInitialized] ){
        _openADTimer = [NSTimer scheduledTimerWithTimeInterval:kOpenADPerSec target:self selector:@selector(checkOpenADReadyState) userInfo:nil repeats:YES];
        [self confiugreLanuchBgView:window];
        return;
      }
      if ( [self.openAD isReady] ){
          
          [self.openAD showAd];
      }
      else
      {
          _openADTimer = [NSTimer scheduledTimerWithTimeInterval:kOpenADPerSec target:self selector:@selector(checkOpenADReadyState) userInfo:nil repeats:YES];
          [self confiugreLanuchBgView:window];
        [self.openAD loadAd];
      }
}

- ( void)confiugreLanuchBgView:(UIWindow *)window{
    UIViewController *vc = [UIViewController new];
    window.rootViewController = vc;
    
    UIImageView *imgView = [UIImageView new];
    imgView.frame = window.bounds;
    [window addSubview:imgView];
    imgView.image = [UIImage imageNamed:@"wlaunch"];
    imgView.contentMode = UIViewContentModeScaleAspectFit;
    _processView = [UIProgressView new];
    _processView.frame = CGRectMake(80, window.frame.size.height - 60, window.frame.size.width - 160, 20);
    _processView.tintColor = [UIColor systemPinkColor];
    [imgView addSubview:_processView];
    
    [vc.view addSubview:imgView];
}

- (void)showOpenAD {
    if ( ![[ALSdk shared] isInitialized] ){
        return;
      }
      if ( [self.openAD isReady] ){
          [self.openAD showAd];
      }
      else
      {
        [self.openAD loadAd];
      }
}

- (void)loadAD:(MAAd *)ad{
    if([ad.adUnitIdentifier isEqualToString:self.openAD.adUnitIdentifier]) {
        [self.openAD loadAd];
    }
    else if ([ad.adUnitIdentifier isEqualToString:self.interstitialAD_Back.adUnitIdentifier]) {
        [self.interstitialAD_Back loadAd];
    }
    else if ([ad.adUnitIdentifier isEqualToString:self.interstitialAD_Save.adUnitIdentifier]) {
        [self.interstitialAD_Save loadAd];
    }
    else if ([ad.adUnitIdentifier isEqualToString:self.interstitialAD_Search.adUnitIdentifier]) {
        [self.interstitialAD_Search loadAd];
    }
}

//#pragma mark - MAAdDelegate Protocol
- (void)didLoadAd:(MAAd *)ad {
    self.retryAttempt_OpenAD = 0;
    self.retryAttempt_saveAD = 0;
    self.retryAttempt_backAD = 0;
    self.retryAttempt_searchAD = 0;
    
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error {
    NSLog(@"加载广告失败.... :%@  err:%@",adUnitIdentifier,error);
    
    if([adUnitIdentifier isEqualToString:self.openAD.adUnitIdentifier]) {
        self.retryAttempt_OpenAD++;
          NSInteger delaySec = pow(2, MIN(6, self.retryAttempt_OpenAD));

          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self.openAD loadAd];
          });
    }
    else if ([adUnitIdentifier isEqualToString:self.interstitialAD_Search.adUnitIdentifier]) {
        self.retryAttempt_searchAD++;
          NSInteger delaySec = pow(2, MIN(6, self.retryAttempt_searchAD));

          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self.interstitialAD_Search loadAd];
          });
    }
    else if ([adUnitIdentifier isEqualToString:self.interstitialAD_Back.adUnitIdentifier]) {
        self.retryAttempt_backAD++;
          NSInteger delaySec = pow(2, MIN(6, self.retryAttempt_backAD));

          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self.interstitialAD_Back loadAd];
          });
    }
    else if ([adUnitIdentifier isEqualToString:self.interstitialAD_Save.adUnitIdentifier]) {
        self.retryAttempt_saveAD++;
          NSInteger delaySec = pow(2, MIN(6, self.retryAttempt_saveAD));

          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delaySec * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [self.interstitialAD_Save loadAd];
          });
    }
}

- (void)didDisplayAd:(MAAd *)ad {
    NSLog(@"成功展示了ad....");
}

- (void)didClickAd:(MAAd *)ad {
    NSLog(@"点击了广告.....");
}

- (void)didHideAd:(MAAd *)ad{
    NSLog(@"隐藏了ad....");
    if (self.callback) {
        self.callback(1);
    }
    
    [self loadAD:ad];
}

- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error{
    NSLog(@"展示广告失败....");
    [self loadAD:ad];
}

@end
