//
//  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>
#import <FirebaseAnalytics/FirebaseAnalytics.h>


//替换为自己需要用到的VC类头文件
#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;
    
//    UILabel *t;
//    t.textColor
}


#pragma mark -------配置firebase
#warning 记得将目录下的GoogleService-Info.plist文件替换为当前app的firebase配置
- (void)configureADByFirebaseWith:(UIWindow *)window {
    [FIRApp configure];
    [FIRAnalytics logEventWithName:@"configureAD_event" parameters:@{@"configureAD":@"1"}];
    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:@"f4d33bc86b44eb24" actionBlock:^(UIViewController * _Nonnull vc) {
        
    }];//第一个一定为开屏插页
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"e0ac389b7746be38" actionBlock:^(UIViewController * _Nonnull vc) {
        AWM_ditViewController *subvc = [AWM_ditViewController new];
        subvc.adIndex = 1;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"a8ecc9c457dee7bf" actionBlock:^(UIViewController * _Nonnull vc) {
        AWM_SearchViewController *subvc = [AWM_SearchViewController new];
        subvc.adIndex = 2;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] addADWithInterstitialId:@"f4231f22c0314229" actionBlock:^(UIViewController * _Nonnull vc) {
        AWM_wallpaperViewController *subvc = [AWM_wallpaperViewController new];
        subvc.adIndex = 3;
        [vc.navigationController pushViewController:subvc animated:NO];
    }];
    
    [[LuxADManager shareInstance] configureADWithAppLovinSDKKey:@"HXOh4UBLahW9KzBBrxqwniKOvfD_JEDJgE9y2rv8DlmJaJ6xPEXUmmJyeAg0xipqdH_EiHg5NsnvfmIHubSu1k"];
    
    __weak typeof(self)weakSelf = self;
    [[LuxADManager shareInstance] showFirstOpenAD:^(NSInteger actionType) {
        [weakSelf configureRootVCWith:window];
    } window:window bgImgName:@"ssa" bgColor:nil];
    
    
}


#pragma mark -------这个地方配置A面正常的VC
- (void)configureRootVCWith:(UIWindow *)window {
    NSString *tab1 = KLS(@"tab1", @"A friendly greeting");
    NSString *tab2 = KLS(@"tab2", @"A friendly greeting");
    NSString *tab3 = KLS(@"tab3", @"A friendly greeting");
    NSString *tab4 = KLS(@"tab4", @"A friendly greeting");
    NSString *tab11 = KLS(@"tab11", @"A friendly greeting");
    NSString *tab22 = KLS(@"tab22", @"A friendly greeting");
    NSString *tab33 = KLS(@"tab33", @"A friendly greeting");
    NSString *tab44 = KLS(@"tab44", @"A friendly greeting");
    AWM_OnePageViewController *wpHome = [[AWM_OnePageViewController alloc] init];
    wpHome.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"" image:[[UIImage imageNamed:tab1] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:tab11] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        UINavigationController *wpHomeNV = [[UINavigationController alloc] initWithRootViewController:wpHome];
    
    AWM_HotViewController *wpHot = [[AWM_HotViewController alloc] init];
    wpHot.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"" image:[[UIImage imageNamed:tab2] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:tab22] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        UINavigationController *wpHotNV = [[UINavigationController alloc] initWithRootViewController:wpHot];
    
    AWM_ditViewController *wpEdit = [[AWM_ditViewController alloc] init];
    wpEdit.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"" image:[[UIImage imageNamed:tab3] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:tab33] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        UINavigationController *wpEditNV = [[UINavigationController alloc] initWithRootViewController:wpEdit];
    AWM_ForMyViewController *wpMy = [[AWM_ForMyViewController alloc] init];
    wpMy.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"" image:[[UIImage imageNamed:tab4] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:tab44] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        UINavigationController *wpMyNV = [[UINavigationController alloc] initWithRootViewController:wpMy];
        
        UITabBarController *tb = [[UITabBarController alloc] init];
        tb.tabBar.backgroundColor = ZH_COLOR_WITH_HEX(0xFFFFFF);
        tb.tabBar.tintColor = [UIColor orangeColor];
    UITabBarAppearance *skappearance = [[UITabBarAppearance alloc] init];
    skappearance.backgroundColor = ZH_COLOR_WITH_HEX(0x6B77F2);
    tb.tabBar.standardAppearance = skappearance;

        tb.viewControllers = @[wpHomeNV,wpHotNV,wpEditNV,wpMyNV];
        tb.selectedIndex = 0;
    window.rootViewController = tb;
    [window makeKeyAndVisible];
}
@end
