//
//  AppDelegate+LuxAppDelegate.m
//  TallPaper
//
//  Created by aaa on 2024/7/30.
//

#import "LuxADConfigure.h"
#import <objc/runtime.h>
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>

#import <Firebase/Firebase.h>
#import <FirebaseCore/FirebaseCore.h>
#import <FirebaseRemoteConfig/FirebaseRemoteConfig.h>



//替换为自己需要用到的VC类头文件
#import "OneVC.h"
#import "twoVC.h"
#import "threeVC.h"
//#import "AWM_OnePageViewController.h"
//#import "AWM_HotViewController.h"
//#import "AWM_ditViewController.h"
//#import "AWM_ForMyViewController.h"
//#import "AWM_SearchViewController.h"
//#import "AWM_wallpaperViewController.h"

@interface LuxADConfigure()
@property (nonatomic,strong) NSTimer *attTimer;

@end

#define ZH_COLOR_WITH_HEX(HEX) [UIColor colorWithRed:((HEX >> 16) & 0xFF) / 255.0f green:((HEX >> 8) & 0xFF) / 255.0f blue:((HEX) & 0xFF) / 255.0f alpha:1.0f]
@implementation LuxADConfigure

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

//检查idfa的att弹框
 - (void)checkATT{
     if (@available(iOS 14.0,*)) {
         [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
             // 获取到权限后，依然使用老方法获取idfa
             if(status == ATTrackingManagerAuthorizationStatusNotDetermined) {
                 
                 if(self.attTimer == nil) {
                     self.attTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(checkATT) userInfo:nil repeats:YES];
                     [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                         if (status != ATTrackingManagerAuthorizationStatusNotDetermined) {
                             NSLog(@"用户已做出选择");
                             [self invalidATTTimer];
                         }
                         else {
                             NSLog(@"用户未做出选择,可能是弹框未弹出...");
                         }
                     }];
                 }
                 
             }
             else{
                 [self invalidATTTimer];
             }
        }];
     }
}


-(void)invalidATTTimer{
    if( self.attTimer ){
        [self.attTimer invalidate];
    }
    self.attTimer = nil;
}


#pragma mark -------配置firebase
#warning 记得将目录下的GoogleService-Info.plist文件替换为当前app的firebase配置
- (void)configureADByFirebaseWith:(UIWindow *)window {
    [FIRApp configure];
    if ([[LuxADManager shareInstance] isADSSMode] ) {
        [self configureADWith:window];
    }
    else {//读取firebase数据
        __weak typeof(self)weakSelf = self;
        FIRRemoteConfig *rc = [FIRRemoteConfig remoteConfig];
        FIRRemoteConfigSettings *rcs = [FIRRemoteConfigSettings new];
        rcs.minimumFetchInterval = 0;
        rc.configSettings = rcs;
        [rc fetchAndActivateWithCompletionHandler:^(FIRRemoteConfigFetchAndActivateStatus status, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (status == FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote) {
                    NSString *localVer = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleShortVersionString"];
                    NSDictionary *value = [[rc configValueForKey:@"isopen"] JSONValue];
                    BOOL isadopen = [value[@"isadopen"] boolValue];
                    NSString *version = value[@"version"];
                    if (!isadopen || ( version && [version isEqualToString:localVer])) {//不展示ad
                        [weakSelf configureRootVCWith:window];
                    }
                    else {
                        [weakSelf configureADWith:window];
                    }
                }
                else {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakSelf configureADByFirebaseWith:window];
                    });
                }
            });
            
        }];
    }
}


#pragma mark -----配置AD
#warning 请把以下的id与key替换为对应项目的max 账户信息; 同时,请将每个actionBlock中的代码改为点击每个广告需要跳转的页面
- (void)configureADWith:(UIWindow *)window {
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"bee9f7039e56cc7a" actionBlock:^(UIViewController * _Nonnull vc) {
        
    }];//第一个一定为开屏插页
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"8fccdfa964b52e26" actionBlock:^(UIViewController * _Nonnull vc) {
        OneVC *subvc = [OneVC new];
        subvc.adIndex = 1;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"bee9f7039e56cc7a" actionBlock:^(UIViewController * _Nonnull vc) {
        twoVC *subvc = [twoVC new];
        subvc.adIndex = 2;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"7baed02646413e44" actionBlock:^(UIViewController * _Nonnull vc) {
        threeVC *subvc = [threeVC new];
        subvc.adIndex = 3;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] configureADWithAppLovinSDKKey:@"NLQHJDx4rcfd5IqhZf9nad2tIqFSH8SSKP3DXD18sTKUvV6tBfrH9_RPCGb6hvEn3NPXJDmUQCnvnKgHIT7Qn4"];
    __weak typeof(self)weakSelf = self;
    [[LuxADManager shareInstance] showFirstOpenAD:^(NSInteger actionType) {
        [weakSelf configureRootVCWith:window];
    } window:window bgImgName:@"logo" bgColor:nil];
    
    
}


#pragma mark -------这个地方配置A面正常的VC
- (void)configureRootVCWith:(UIWindow *)window {

        NSString *hasLaunchedBeforeKey = @"hasLaunchedBefore";
       
    window.frame = [UIScreen mainScreen].bounds;
        [UNUserNotificationCenter currentNotificationCenter].delegate = self;

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

            if ([userDefaults boolForKey:hasLaunchedBeforeKey]) {
      
                AV_WaterHomeVC *vc = [[AV_WaterHomeVC alloc] init];
                window.rootViewController = [[AV_NAVVC alloc] initWithRootViewController:vc];
                
                
            } else {
                // 第一次启动
                AV_SelectGenderVC *vc = [[AV_SelectGenderVC alloc] init];
                window.rootViewController = [[AV_NAVVC alloc] initWithRootViewController:vc];
                [userDefaults setBool:YES forKey:hasLaunchedBeforeKey];
                NSDate *currentDate = [NSDate date];
                [userDefaults setObject:currentDate forKey:@"savedDate"];

            }
        
}




@end
