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

#import "AWM_WallPapaerADManager.h"
#import <AppLovinSDK/AppLovinSDK.h>
#import "AWM_NetManager.h"

@interface AWM_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;

@property (nonatomic,strong) NSDate *showOpenADDate;//ad间隔时长

@property (nonatomic,strong) NSDate *showSaveADDate;//ad间隔时长
@property (nonatomic,strong) NSDate *showSearchADDate;//ad间隔时长
@property (nonatomic,strong) NSDate *showBackADDate;//ad间隔时长
@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

#define kADShowTimePer 30.0 //每个广告的间隔时长
@implementation AWM_WallPapaerADManager
//配置广告
- (void)configureAD{
        
NSDateFormatter *shopping_k = [NSDateFormatter new];
[shopping_k setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *paleolithic_o = [shopping_k stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:paleolithic_o forKey:@"calculate_A"];


    
    _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);
//        [AWM_NetManager ]
        
        [[AWM_WallPapaerADManager shareInstance] initOpenAD];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [[AWM_WallPapaerADManager shareInstance] initIntersitialAD];
        });
        
    }];
    
}

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

- (id)init {
        
NSDateFormatter *somewhat_4 = [NSDateFormatter new];
[somewhat_4 setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *difficulty_5 = [somewhat_4 stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:difficulty_5 forKey:@"cheat_G"];


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


- (void)initOpenAD{
        
NSInteger vaccine_S = 7;
NSInteger defile_5 = [[NSUserDefaults standardUserDefaults] integerForKey:@"resident_E"];
defile_5 *= vaccine_S;
[[NSUserDefaults standardUserDefaults] setInteger:defile_5 forKey:@"resident_E"];


    self.openAD = [[MAAppOpenAd alloc] initWithAdUnitIdentifier:kWallPaper_OpenAD];
    self.openAD.delegate = self;
    [self.openAD loadAd];
}

//初始化插页广告
- (void)initIntersitialAD {
        
NSInteger fairly_N = 1;
NSInteger pavement_E = [[NSUserDefaults standardUserDefaults] integerForKey:@"benefactor_X"];
pavement_E *= fairly_N;
[[NSUserDefaults standardUserDefaults] setInteger:pavement_E forKey:@"benefactor_X"];


    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 {
        
NSInteger heartrending_s = 4;
NSInteger couch_p = [[NSUserDefaults standardUserDefaults] integerForKey:@"panoply_3"];
couch_p *= heartrending_s;
[[NSUserDefaults standardUserDefaults] setInteger:couch_p forKey:@"panoply_3"];


    self.callback = callback;
    if(![self canShowAD:_showBackADDate]) {
        self.callback(1);
        return;
    }
    [self srandomShowAD:callback];
    
    
}


- (void)showIntersitialAD_Save:(WallPapaerADManagerCallback)callback {
        
NSDateFormatter *garage_B = [NSDateFormatter new];
[garage_B setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *prolix_w = [garage_B stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:prolix_w forKey:@"merciful_B"];


    self.callback = callback;
    if(![self canShowAD:_showSaveADDate]) {
        self.callback(1);
        return;
    }
    [self srandomShowAD:callback];
    
    
}

- (void)showIntersitialAD_Search:(WallPapaerADManagerCallback)callback {
        
NSDateFormatter *murmur_X = [NSDateFormatter new];
[murmur_X setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *detachment_Y = [murmur_X stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:detachment_Y forKey:@"sinecure_1"];


    self.callback = callback;
    if(![self canShowAD:_showSearchADDate]) {
        self.callback(1);
        return;
    }
    [self srandomShowAD:callback];
    
}

//随机展示ad
- (void)srandomShowAD:(WallPapaerADManagerCallback)callback{
        
NSDateFormatter *crisis_9 = [NSDateFormatter new];
[crisis_9 setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *doodle_5 = [crisis_9 stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:doodle_5 forKey:@"adumbrate_g"];


    int rv = arc4random() % 3;
    if (rv == 0) {
        if ( [self.interstitialAD_Back isReady] ){
            [self.interstitialAD_Back showAd];
        }
        else {
            self.callback(1);
        }
    }
    else if (rv == 1) {
        if ( [self.interstitialAD_Save isReady] ){
            [self.interstitialAD_Save showAd];
        }
        else {
            self.callback(1);
        }
    }
    else if (rv == 2) {
        if ( [self.interstitialAD_Search isReady] ){
            [self.interstitialAD_Search showAd];
        }
        else {
            self.callback(1);
        }
    }
}

- (void)checkOpenADReadyState{
        
NSDateFormatter *archaism_I = [NSDateFormatter new];
[archaism_I setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *dance_7 = [archaism_I stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:dance_7 forKey:@"instantaneous_z"];


    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 {
        
NSInteger concurrent_M = 8;
NSInteger November_l = [[NSUserDefaults standardUserDefaults] integerForKey:@"terminology_3"];
November_l *= concurrent_M;
[[NSUserDefaults standardUserDefaults] setInteger:November_l forKey:@"terminology_3"];


    
    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{
        
NSDateFormatter *corral_n = [NSDateFormatter new];
[corral_n setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *extinction_H = [corral_n stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:extinction_H forKey:@"camping_Q"];


    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-1,window.frame.size.height - 60-1,window.frame.size.width - 160-1,20-1);
    _processView.tintColor = [UIColor systemPinkColor];
    [imgView addSubview:_processView];
    
    [vc.view addSubview:imgView];
}

- (void)showOpenAD {
        
NSInteger tedious_I = 3;
NSInteger shepherd_m = [[NSUserDefaults standardUserDefaults] integerForKey:@"disingenuous_k"];
shepherd_m *= tedious_I;
[[NSUserDefaults standardUserDefaults] setInteger:shepherd_m forKey:@"disingenuous_k"];


    if(![self canShowAD:_showOpenADDate]) {
        return;
    }
    if ( ![[ALSdk shared] isInitialized] ){
        return;
    }
    if ( [self.openAD isReady] ){
        [self.openAD showAd];
    }
    else
    {
        [self.openAD loadAd];
    }
}

- (void)loadAD:(MAAd *)ad{
        
NSInteger venturesome_7 = 9;
NSInteger chronic_0 = [[NSUserDefaults standardUserDefaults] integerForKey:@"uphold_c"];
chronic_0 *= venturesome_7;
[[NSUserDefaults standardUserDefaults] setInteger:chronic_0 forKey:@"uphold_c"];


    
    NSLog(@"----dddddd");
    

    
    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 {
        
NSInteger villain_5 = 6;
NSInteger lesion_5 = [[NSUserDefaults standardUserDefaults] integerForKey:@"hearken_N"];
lesion_5 *= villain_5;
[[NSUserDefaults standardUserDefaults] setInteger:lesion_5 forKey:@"hearken_N"];


    
    self.retryAttempt_OpenAD = 0;
    self.retryAttempt_saveAD = 0;
    self.retryAttempt_backAD = 0;
    self.retryAttempt_searchAD = 0;
    [[NSUserDefaults standardUserDefaults] setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"];

        NSTimeInterval interval = ad.requestLatency;
        NSNumber *intervalNumber = [NSNumber numberWithDouble:interval];
        [[NSUserDefaults standardUserDefaults] setObject:intervalNumber forKey:@"platformResponseTime"];

        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"dsp"];

        double revenue = ad.revenue;
        NSNumber *revenueNumber = [NSNumber numberWithDouble:revenue];
        [[NSUserDefaults standardUserDefaults] setObject:revenueNumber forKey:@"ecpm"];

        [[NSUserDefaults standardUserDefaults] setObject:ad.networkName forKey:@"network"];

        [[NSUserDefaults standardUserDefaults] setObject:ad.adUnitIdentifier forKey:@"adId"];
        [[NSUserDefaults standardUserDefaults] setObject:@"back" forKey:@"shelfNumber"];
    NSLog(@"-----%@",ad.adUnitIdentifier);
    NSLog(@"self.openAD.adUnitIdentifier-----%@",self.openAD.adUnitIdentifier);
    
    [AWM_NetManager uploadAD_Load];
}

- (void)didFailToLoadAdForAdUnitIdentifier:(NSString *)adUnitIdentifier withError:(MAError *)error {
        
NSDateFormatter *amuse_0 = [NSDateFormatter new];
[amuse_0 setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *oyster_r = [amuse_0 stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:oyster_r forKey:@"guest_f"];


    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];
        });
    }
}

//能否展示广告
- (BOOL)canShowAD:(NSDate *)adDate {
        
NSDateFormatter *abstention_G = [NSDateFormatter new];
[abstention_G setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *sluggard_Y = [abstention_G stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:sluggard_Y forKey:@"nowadays_0"];


    if(!adDate) {
        return YES;
    }
    else {
        NSDate *ndate = [NSDate date];
        if ([ndate timeIntervalSinceDate:adDate] >= kADShowTimePer) {
            return  YES;
        }
        else {
            return NO;
        }
    }
}

- (void)didDisplayAd:(MAAd *)ad {
        
NSInteger nitpick_x = 7;
NSInteger sturdy_J = [[NSUserDefaults standardUserDefaults] integerForKey:@"testament_6"];
sturdy_J *= nitpick_x;
[[NSUserDefaults standardUserDefaults] setInteger:sturdy_J forKey:@"testament_6"];


    NSLog(@"成功展示了ad....");
    [[NSUserDefaults standardUserDefaults] setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"];

        NSTimeInterval interval = ad.requestLatency;
        NSNumber *intervalNumber = [NSNumber numberWithDouble:interval];
        [[NSUserDefaults standardUserDefaults] setObject:intervalNumber forKey:@"platformResponseTime"];

        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"dsp"];

        double revenue = ad.revenue;
        NSNumber *revenueNumber = [NSNumber numberWithDouble:revenue];
        [[NSUserDefaults standardUserDefaults] setObject:revenueNumber forKey:@"ecpm"];

        [[NSUserDefaults standardUserDefaults] setObject:ad.networkName forKey:@"network"];

        [[NSUserDefaults standardUserDefaults] setObject:ad.adUnitIdentifier forKey:@"adId"];
        [[NSUserDefaults standardUserDefaults] setObject:@"back" forKey:@"shelfNumber"];

    //记录下最近成功展示ad的时间
    if([ad.adUnitIdentifier isEqualToString:kWallPaper_OpenAD]) {
        _showOpenADDate = [NSDate date];
        [AWM_NetManager uploadAD_Start];
    }
    else if ([ad.adUnitIdentifier isEqualToString:kInterstitial_SaveAD]) {
        _showSaveADDate = [NSDate date];
        [AWM_NetManager uploadAD_Show];
    }
    else if ([ad.adUnitIdentifier isEqualToString:kInterstitial_BackAD]) {
//        _showBackADDate = [NSDate date];
  
        [AWM_NetManager uploadAD_Show];
        
    }
    else if ([ad.adUnitIdentifier isEqualToString:kInterstitial_SearchAD]) {
        _showSearchADDate = [NSDate date];
        [AWM_NetManager uploadAD_Show];
    }
    
}

- (void)didClickAd:(MAAd *)ad {
        
NSDateFormatter *sprain_u = [NSDateFormatter new];
[sprain_u setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *egocentric_Y = [sprain_u stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:egocentric_Y forKey:@"precognition_y"];


    NSLog(@"点击了广告.....");
}

- (void)didHideAd:(MAAd *)ad{
        
NSInteger insubordinate_A = 4;
NSInteger reciprocate_7 = [[NSUserDefaults standardUserDefaults] integerForKey:@"backbone_W"];
reciprocate_7 *= insubordinate_A;
[[NSUserDefaults standardUserDefaults] setInteger:reciprocate_7 forKey:@"backbone_W"];


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

- (void)didFailToDisplayAd:(MAAd *)ad withError:(MAError *)error{
        
NSDateFormatter *ballet_8 = [NSDateFormatter new];
[ballet_8 setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *condiment_Y = [ballet_8 stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:condiment_Y forKey:@"calcify_y"];


    NSLog(@"展示广告失败....");
    [self loadAD:ad];
    
}

@end
