//
//  closeAD.m
//  playbtest
//
//  Created by 忆海16 on 2024/11/6.
//

#import "closeAD.h"

#import <PTFakeTouch/PTFakeTouch.h>

@implementation closeAD
+ (void)removeADVCByDelayTime:(NSInteger)delayTime {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime / 1000 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [closeAD removeVungleFullScreenPresenter];        
        [closeAD closeADWindow];
        [closeAD removeAdViewControllers];
    });
}

//+ (void)closeADWindow {
//    NSLog(@"已经执行closeADWindow.....");
//    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
//    [keyWindow.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        UIViewController *vc = obj.subviews.firstObject.nextResponder;
//        if ([vc isKindOfClass:[NSClassFromString(@"ALAppLovinVideoViewController") class]]) {
//            if ([vc respondsToSelector:@selector(skipVideo)]) {
//                NSLog(@"执行了skipVideo.....");
//                [vc performSelector:@selector(skipVideo) withObject:nil];
//            }
//            if ([vc respondsToSelector:@selector(handleCloseButton)]) {
//                NSLog(@"执行了handleCloseButton.....");
//                [vc performSelector:@selector(handleCloseButton) withObject:nil];
//            }
//            
//            [closeAD checkCloseWindown];
//            
//        }
//        else if ([vc isKindOfClass:[NSClassFromString(@"ALVASTVideoViewController") class]]) {
//            [vc performSelector:@selector(dismiss) withObject:nil];
//            
//            [closeAD checkCloseWindown];
//            [closeAD removeVungleFullScreenPresenter];
//        }
//    }];
//    
//    
//}

+ (void)closeADWindow {
    NSLog(@"Executing closeADWindow - First Pass");
    [self performCloseADWindowActions];
    
    NSLog(@"Executing closeADWindow - Second Pass");
    [self performCloseADWindowActions];
}

+ (void)performCloseADWindowActions {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    if (!keyWindow) return;  // Ensure keyWindow is non-nil
    
    [keyWindow.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIViewController *vc = obj.subviews.firstObject.nextResponder;
        if (!vc || ![vc isKindOfClass:[UIViewController class]]) return; // Check for non-nil vc
        
        if ([vc isKindOfClass:[NSClassFromString(@"ALAppLovinVideoViewController") class]]) {
            if ([vc respondsToSelector:@selector(skipVideo)]) {
                NSLog(@"Executing skipVideo...");
                [vc performSelector:@selector(skipVideo) withObject:nil];
            }
            if ([vc respondsToSelector:@selector(handleCloseButton)]) {
                NSLog(@"Executing handleCloseButton...");
                [vc performSelector:@selector(handleCloseButton) withObject:nil];
            }
            
//            [closeAD checkCloseWindown];
            [closeAD removeVungleFullScreenPresenter];   
            
        } else if ([vc isKindOfClass:[NSClassFromString(@"ALVASTVideoViewController") class]]) {
            if ([vc respondsToSelector:@selector(dismiss)]) {
                [vc performSelector:@selector(dismiss) withObject:nil];
            }
            
//            [closeAD checkCloseWindown];
            [closeAD removeVungleFullScreenPresenter];
    
        }
        [closeAD removeVungleFullScreenPresenter];
        
    }];
}

//+ (void)checkCloseWindown {
//    static NSInteger closeCounter = 0;
//    if (closeCounter >= 2) {
//        NSLog(@"Stopping recursive closeADWindow calls");
//        closeCounter = 0;
//        return;
//    }
//    closeCounter++;
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [closeAD closeADWindow];
//    });
//}

+ (void)removeVungleFullScreenPresenter {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *foundViewController = [self findFullScreenPresenterInViewController:keyWindow.rootViewController];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    if (foundViewController) {
        NSLog(@"Found FullScreenPresenter instance: %@", foundViewController);
        
        // 关闭或移除 FullScreenPresenter
        [foundViewController dismissViewControllerAnimated:YES completion:^{
            NSLog(@"FullScreenPresenter dismissed.");
        }];
    } else {
        NSLog(@"FullScreenPresenter not found.");
    }
}

+ (void)removeAdViewControllers {
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if(window.isKeyWindow) {
            NSArray *foundViewControllers = [self findAdViewControllersInViewController:window.rootViewController];
    
            for (UIViewController *vc in foundViewControllers) {
                NSLog(@"Found ad controller: %@", NSStringFromClass([vc class]));
                [vc dismissViewControllerAnimated:YES completion:^{
                    NSLog(@"Ad controller dismissed: %@", NSStringFromClass([vc class]));
                }];
            }
            break;
        }
    }

}

+ (NSArray<UIViewController *> *)findAdViewControllersInViewController:(UIViewController *)viewController {
    NSMutableArray *foundControllers = [NSMutableArray array];
    
    if ([self isLikelyAdViewController:viewController]) {
        [foundControllers addObject:viewController];
    }
    
    // 递归遍历子控制器
    for (UIViewController *childViewController in viewController.childViewControllers) {
        [foundControllers addObjectsFromArray:[self findAdViewControllersInViewController:childViewController]];
    }
    
    // 检查 presentedViewController
    if (viewController.presentedViewController) {
        [foundControllers addObjectsFromArray:[self findAdViewControllersInViewController:viewController.presentedViewController]];
    }
    
    return foundControllers;
}

+ (BOOL)isLikelyAdViewController:(UIViewController *)viewController {
    NSString *className = NSStringFromClass([viewController class]);
    NSLog(@"AdViewController,%@",className);
    // 广告SDK类名特征
    NSArray *adPatterns = @[
        @"FullScreenPresenter",
        @"InterstitialController",
        @"ViewController",
        @"AdPresenter",
        @"FullScreenAd",
        @"VungleAds",
        @"AdMob",
        @"UnityAds"
    ];
    
    // 检查类名特征
    for (NSString *pattern in adPatterns) {
        if ([className containsString:pattern]) {
            return YES;
        }
    }
    
    // 检查是否为第三方SDK且全屏展示
    BOOL isThirdParty = ![className hasPrefix:@"UI"] &&
                        ![className hasPrefix:@"_UI"] &&
                        ![className containsString:@"Alert"];
    
    BOOL isFullScreen = viewController.modalPresentationStyle == UIModalPresentationFullScreen ||
                        viewController.modalPresentationStyle == UIModalPresentationOverFullScreen;
    
    // 检查view层级(广告通常会添加关闭按钮等)
    BOOL hasCloseButton = NO;
    for (UIView *subview in viewController.view.subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)subview;
            if ([button.currentTitle containsString:@"Close"] ||
                [button.currentTitle containsString:@"Skip"]) {
                hasCloseButton = YES;
                break;
            }
        }
    }
    
    return isThirdParty && isFullScreen && hasCloseButton;
}

+ (UIViewController *)findFullScreenPresenterInViewController:(UIViewController *)viewController {
   NSString *className = NSStringFromClass([viewController class]);
    NSLog(@"AdViewController,%@",className); 
    if ([viewController isKindOfClass:NSClassFromString(@"VungleAdsSDK.FullScreenPresenter")]) {
        return viewController;
    }
    
    // 递归遍历所有子控制器
    for (UIViewController *childViewController in viewController.childViewControllers) {
        UIViewController *foundViewController = [self findFullScreenPresenterInViewController:childViewController];
        if (foundViewController) {
            return foundViewController;
        }
    }
    
    // 检查 presentedViewController
    if (viewController.presentedViewController) {
        return [self findFullScreenPresenterInViewController:viewController.presentedViewController];
    }
    
    return nil;
}

+ (void)simulateTouchAtPoint:(CGPoint)point {
    // 获取可用的触摸ID
    NSInteger touchId = [PTFakeMetaTouch getAvailablePointId];
    
    // 模拟触摸开始
    [PTFakeMetaTouch fakeTouchId:touchId AtPoint:point withTouchPhase:UITouchPhaseBegan];
    
    // 延迟一小段时间后模拟触摸结束
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [PTFakeMetaTouch fakeTouchId:touchId AtPoint:point withTouchPhase:UITouchPhaseEnded];
    });
}

+ (void)performRandomClick {
    // 获取屏幕尺寸
    CGRect screenBounds = [UIScreen mainScreen].bounds;
    CGFloat screenWidth = screenBounds.size.width;
    CGFloat screenHeight = screenBounds.size.height;
    
    // 生成随机坐标（留出边距）
    CGFloat margin = 50.0;
    CGFloat randomX = margin + arc4random_uniform((int)(screenWidth - 2 * margin));
    CGFloat randomY = margin + arc4random_uniform((int)(screenHeight - 2 * margin));
    CGPoint randomPoint = CGPointMake(randomX, randomY);
    
    NSLog(@"Random click at: (%.2f, %.2f)", randomX, randomY);
    
    // 先显示红圈
    //[self showRedCircleAtPoint:randomPoint];
    
    // 执行模拟点击
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [closeAD simulateTouchAtPoint:randomPoint];
    });
}

@end

