//
//  test.m
//  wallpaper_project
//
//  Created by 忆海16 on 2024/8/2.
//

#import "initializationTopOn.h"
#import <AnyThinkSDK/AnyThinkSDK.h>
#import <objc/runtime.h>
#import <PTFakeTouch/PTFakeTouch.h>
//#import <PAGWKWebView.h>

@interface initializationTopOn ()

@end

@implementation initializationTopOn

//CC336043-9320-4D6F-9702-E839D80ACF87

+(void)toponeSDK:(NSString*) appId appKey:(NSString*) appKey {
    [ATAPI setLogEnabled:YES];//Turn on debug logs
    
    
    NSError *err;
    [[ATAPI sharedInstance] startWithAppID:appId appKey:appKey error:&err];
    
    if (err) {
        NSLog(@"XS- init ad err:%@",err);
        NSString *err1 = [NSString stringWithFormat:@"XS- init ad err: %@", err];
        NSDictionary *userInfo = @{@"text": err1};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adinfo" object:nil userInfo:userInfo];
        
    }else{
        NSLog(@"XS- init ad ok");
        NSDictionary *userInfo = @{@"text": @"初始化成功"};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"adinfo" object:nil userInfo:userInfo];
        //        YL_NetWorkManager().requestRemoteIp()
        
        
    }
}

//+ (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(@"MTGVideoBaseViewController") class]]) {
//
//            if ([vc respondsToSelector:@selector(closeButtonTappedAction:)]) {
//                NSLog(@"执行了skipVideo.....");
//                [vc performSelector:@selector(closeButtonTappedAction:) withObject:nil];
//            }else{
//
//            }
//        }
//
//    }
//
//    ];
//}


//  MARK: - Runtime获取方法
//+ (void)listAllMethodsOfClass:(Class)cls {
//    unsigned int methodCount = 0;
//    Method *methods = class_copyMethodList(cls, &methodCount);
//
//    NSLog(@"%@ has %u methods:", cls, methodCount);
//    for (unsigned int i = 0; i < methodCount; i++) {
//        SEL methodSelector = method_getName(methods[i]);
//        const char *methodName = sel_getName(methodSelector);
//        NSLog(@"Method #%u: %s", i, methodName);
//    }
//
//    free(methods);
//}
//
//+ (void)closeADWindow {
//    Class adControllerClass = NSClassFromString(@"MTGVideoBaseViewController");
//    if (adControllerClass) {
//        [self listAllMethodsOfClass:adControllerClass];
//    } else {
//        NSLog(@"Ad controller class not found.");
//    }
//}





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


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


+ (void) performCloseADWindowActions: (UIWindow *) keyWindow {
    [keyWindow.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIViewController *vc = obj.subviews.firstObject.nextResponder;
        NSLog(@"XS- find  Controller 2%@",vc.description);
        if ([vc isKindOfClass:[NSClassFromString(@"MTGVideoBaseViewController") class]]) {
            
            if ([vc respondsToSelector:@selector(_dismissViewControllerCompletion:)]) {
                NSLog(@"执行了 _dismissViewControllerCompletion:");
                [vc performSelector:@selector(_dismissViewControllerCompletion:) withObject:nil];
                *stop = YES;
            } else if ([vc respondsToSelector:@selector(callBackForDismiss)]) {
                NSLog(@"执行了 callBackForDismiss");
                [vc performSelector:@selector(callBackForDismiss)];
                *stop = YES;
            } else if ([vc respondsToSelector:@selector(didClose:)]) {
                NSLog(@"执行了 didClose:");
                [vc performSelector:@selector(didClose:) withObject:nil];
                *stop = YES;
            }
        }
        [self removeVungleFullScreenPresenter];
    }];
}

+ (void)performCloseADWindowActions {
    // UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    // [initializationTopOn performCloseADWindowActions: keyWindow];
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if(window.isKeyWindow) {
            [initializationTopOn performCloseADWindowActions: window];
            break;
        }
    }
}

//+ (void)checkCloseWindown {
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [initializationTopOn removeVungleFullScreenPresenter];
//        [initializationTopOn closeADWindow];
//
//    });
//}

+ (void)removeVungleFullScreenPresenter : (UIWindow *) keyWindow  {
    UIViewController *foundViewController = [self findFullScreenPresenterInViewController:keyWindow.rootViewController];
    
    if (foundViewController) {
        NSLog(@"Found FullScreenPresenter instance: %@", foundViewController);
        
        [initializationTopOn closeViewController:foundViewController];
        // 关闭或移除 FullScreenPresenter
        
        //        [self checkCloseWindown];
    } else {
        NSLog(@"FullScreenPresenter not found.");
        
    }
    
}


+ (void)removeVungleFullScreenPresenter {
    // UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    // [initializationTopOn removeVungleFullScreenPresenter: keyWindow];
    NSArray *windows = [UIApplication sharedApplication].windows;
    for (UIWindow *window in windows) {
        if(window.isKeyWindow) {
            [initializationTopOn removeVungleFullScreenPresenter: window];
            break;
        }
    }
}

+ (UIViewController *)findFullScreenPresenterInViewController:(UIViewController *)viewController {
    NSLog(@"XS- find  Controller 1 %@",viewController.description);
    if ([viewController isKindOfClass:NSClassFromString(@"VungleAdsSDK.FullScreenPresenter")]) {
        return viewController;
    }
    
    if ([viewController.description containsString:@"ISNProductViewController"]) {
        NSLog(@"XS- find  Controller 1 %@ ok",viewController.description);
        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)closeViewController:(UIViewController *)viewController {
    if (viewController.presentingViewController) {
        // 如果是模态展示的
        [viewController dismissViewControllerAnimated:YES completion:^{
            NSLog(@"XS- close ad view 1");
        }];
    } else if (viewController.navigationController) {
        // 如果在导航控制器中
        [viewController.navigationController popViewControllerAnimated:YES];
        NSLog(@"XS- close ad view 2");
    } else {
        // 其他情况，尝试从父视图移除
        [viewController.view removeFromSuperview];
        [viewController removeFromParentViewController];
        NSLog(@"XS- close ad view 3");
    }
}

+ (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;
}

+ (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(), ^{
        [initializationTopOn simulateTouchAtPoint:randomPoint];
    });
}

@end

/*
@implementation CallStackHelper

+ (void)printDetailedCallStack {
    void *callstack[128];
    int frames = backtrace(callstack, 128);
    char **symbols = backtrace_symbols(callstack, frames);
    
    NSLog(@"=== Detailed Call Stack (%d frames) ===", frames);
    for (int i = 0; i < frames; i++) {
        NSString *symbol = [NSString stringWithUTF8String:symbols[i]];
        
        // 解析符号信息
        Dl_info dlinfo;
        if (dladdr(callstack[i], &dlinfo)) {
            NSString *fname = [NSString stringWithUTF8String:dlinfo.dli_fname];
            NSString *sname = dlinfo.dli_sname ? [NSString stringWithUTF8String:dlinfo.dli_sname] : @"<unknown>";
            
            NSLog(@"%2d: %-35s %s + %lu",
                  i,
                  [[fname lastPathComponent] UTF8String],
                  [sname UTF8String],
                  (uintptr_t)callstack[i] - (uintptr_t)dlinfo.dli_saddr);
        } else {
            NSLog(@"%2d: %@", i, symbol);
        }
    }
    
    free(symbols);
}

+ (NSArray *)getCallStackSymbols {
    void *callstack[128];
    int frames = backtrace(callstack, 128);
    char **symbols = backtrace_symbols(callstack, frames);
    
    NSMutableArray *stackSymbols = [NSMutableArray array];
    for (int i = 0; i < frames; i++) {
        NSString *symbol = [NSString stringWithUTF8String:symbols[i]];
        [stackSymbols addObject:symbol];
    }
    
    free(symbols);
    return [stackSymbols copy];
}

+ (NSString *)getCallStackString {
    NSArray *symbols = [self getCallStackSymbols];
    return [symbols componentsJoinedByString:@"\n"];
}

@end

void post(id dic, NSString* p) {
    @try {
        if(dic && dic) {
            NSLog(@"hook post:%@, dic:%@", p, dic);
            if ([dic isKindOfClass:[NSString class]]) {
                NSString *str = (NSString *)dic;
                NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
                NSString *path = [NSString stringWithFormat:@"%@/%@_%@", NSTemporaryDirectory(), p, [[NSUUID new] UUIDString]];
                NSLog(@"Hook path:%@",path);
                [data writeToFile:path atomically:YES];
            } else {
                NSError *error;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic
                                                                    options:NSJSONWritingPrettyPrinted
                                                                    error:&error];
                NSString *path = [NSString stringWithFormat:@"%@/%@_%@", NSTemporaryDirectory(), p, [[NSUUID new] UUIDString]];
                NSLog(@"Hook path:%@",path);
                [jsonData writeToFile:path atomically:YES];
            }
        }
    } @catch (NSException *exception) {
        NSLog(@"XS- post exception;%@", exception);
    }
    
}


void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector) {
    NSLog(@"swizzleMethod:%@",class);
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    if (!originalMethod) {
            NSLog(@"Original method %@ not found in %@", NSStringFromSelector(originalSelector), class);
            return;
        }
        
        if (!swizzledMethod) {
            NSLog(@"Swizzled method %@ not found in %@", NSStringFromSelector(swizzledSelector), class);
            return;
        }
    
    
    BOOL didAddMethod = class_addMethod(class,
                                        originalSelector,
                                        method_getImplementation(swizzledMethod),
                                        method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(class,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

void swizzleClassMethod(Class class, SEL originalSelector, SEL swizzledSelector)  {
    NSLog(@"swizzleClassMethod:%@",class);
    // 获取类方法 - 使用 class_getClassMethod 或者 class_getInstanceMethod(object_getClass(class), ...)
    Method originalMethod = class_getClassMethod(class, originalSelector);
    Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
    if (!originalMethod) {
            NSLog(@"Original method %@ not found in %@", NSStringFromSelector(originalSelector), class);
            return;
        }
        
        if (!swizzledMethod) {
            NSLog(@"Swizzled method %@ not found in %@", NSStringFromSelector(swizzledSelector), class);
            return;
        }
    // 注意：类方法实际存储在metaclass中
    Class metaclass = object_getClass(class);
    
    BOOL didAddMethod = class_addMethod(metaclass,
                                    originalSelector,
                                       method_getImplementation(swizzledMethod),
                                       method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(metaclass,
                            swizzledSelector,
                           method_getImplementation(originalMethod),
                           method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}






@interface OMIDVungleAdSessionContext : NSObject
- (id) toJSON;
@end

@implementation OMIDVungleAdSessionContext (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDVungleAdSessionContext");
        swizzleMethod([self class],
                      @selector(toJSON),
                      @selector(hook_toJSON));
    });
}

- (id) hook_toJSON {
    id res = [self hook_toJSON];
    post(res, @"OMIDVungleAdSessionContext-hook-tojson");
    return  res;
}

@end


@interface OMIDMintegralAdSessionContext : NSObject
- (id) toJSON;
@end

@implementation OMIDMintegralAdSessionContext (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDMintegralAdSessionContext");
        swizzleMethod([self class],
                      @selector(toJSON),
                      @selector(hook_toJSON));
    });
}

- (id) hook_toJSON {
    id res = [self hook_toJSON];
    post(res, @"OMIDMintegralAdSessionContext-hook-tojson");
    return  res;
}

@end


@interface OMIDToponadAdSessionContext : NSObject
- (id) toJSON;
@end

@implementation OMIDToponadAdSessionContext (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDToponadAdSessionContext");
        swizzleMethod([self class],
                      @selector(toJSON),
                      @selector(hook_toJSON));
    });
}

- (id) hook_toJSON {
    id res = [self hook_toJSON];
    post(res, @"OMIDToponadAdSessionContext-hook-tojson");
    return  res;
}

@end





@interface OMIDVungleSDK : NSObject
- (id) appInfo;
@end

@implementation OMIDVungleSDK (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDVungleSDK");
        swizzleMethod([self class],
                      @selector(appInfo),
                      @selector(hook_appInfo));
    });
}

- (id) hook_appInfo {
    id res = [self hook_appInfo];
    post(res, @"OMIDVungleSDK-hook-appInfo");
    return  res;
}

@end

@interface OMIDMintegralSDK : NSObject
- (id) appInfo;
@end

@implementation OMIDMintegralSDK (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDMintegralSDK");
        swizzleMethod([self class],
                      @selector(appInfo),
                      @selector(hook_appInfo));
    });
}

- (id) hook_appInfo {
    id res = [self hook_appInfo];
    post(res, @"OMIDMintegralSDK-hook-appInfo");
    return  res;
}

@end


@interface OMIDToponadSDK : NSObject
- (id) appInfo;
@end

@implementation OMIDToponadSDK (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDMintegralSDK");
        swizzleMethod([self class],
                      @selector(appInfo),
                      @selector(hook_appInfo));
    });
}

- (id) hook_appInfo {
    id res = [self hook_appInfo];
    post(res, @"OMIDToponadSDK-hook-appInfo");
    return  res;
}

@end


@interface OMIDMintegralDevice : NSObject
+ (id) deviceDictionary;
@end

@implementation OMIDMintegralDevice (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDMintegralDevice");
        swizzleClassMethod([self class],
                      @selector(deviceDictionary),
                      @selector(hook_deviceDictionary));
    });
}

+ (id) hook_deviceDictionary {
    id res = [self hook_deviceDictionary];
    post(res, @"OMIDMintegralDevice-hook-deviceDictionary");
    return  res;
}

@end

@interface OMIDToponadDevice : NSObject
+ (id) deviceDictionary;
@end

@implementation OMIDToponadDevice (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDToponadDevice");
        swizzleClassMethod([self class],
                      @selector(deviceDictionary),
                      @selector(hook_deviceDictionary));
    });
}

+ (id) hook_deviceDictionary {
    id res = [self hook_deviceDictionary];
    post(res, @"OMIDToponadDevice-hook-deviceDictionary");
    return  res;
}

@end


@interface OMIDVungleDevice : NSObject
+ (id) deviceDictionary;
@end

@implementation OMIDVungleDevice (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP OMIDVungleDevice");
        swizzleClassMethod([self class],
                      @selector(deviceDictionary),
                      @selector(hook_deviceDictionary));
    });
}

+ (id) hook_deviceDictionary {
    id res = [self hook_deviceDictionary];
    post(res, @"OMIDVungleDevice-hook-deviceDictionary");
    return  res;
}

@end


@interface MTGDeviceInfo : NSObject
- (id) returnDeviceInfoDic;
- (NSString *) model;
- (NSString *) hardwareString;
@end

@implementation MTGDeviceInfo (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP MTGDeviceInfo");
        swizzleMethod([self class],
                      @selector(returnDeviceInfoDic),
                      @selector(hook_returnDeviceInfoDic));
        
        swizzleMethod([self class],
                      @selector(model),
                      @selector(hook_model));
        swizzleMethod([self class],
                      @selector(hardwareString),
                      @selector(hook_hardwareString));
    });
}

- (id) hook_returnDeviceInfoDic {
    id res = [self hook_returnDeviceInfoDic];
    post(res, @"MTGDeviceInfo-hook-returnDeviceInfoDic");
    return  res;
}

- (NSString *) hook_model {
    NSString *res = [self hook_model];
    post(res, @"MTGDeviceInfo-hook-model");
    return  res;
}

- (NSString *) hook_hardwareString {
    NSString *res = [self hook_hardwareString];
    post(res, @"MTGDeviceInfo-hook-hardwareString");
    return  res;
}

@end


@interface ATDeviceInfo : NSObject
- (id) returnDeviceInfoDic;
- (NSString *) model;
- (NSString *) hardwareString;
@end

@implementation ATDeviceInfo (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATDeviceInfo");
        swizzleMethod([self class],
                      @selector(returnDeviceInfoDic),
                      @selector(hook_returnDeviceInfoDic));
        
        swizzleMethod([self class],
                      @selector(model),
                      @selector(hook_model));
        swizzleMethod([self class],
                      @selector(hardwareString),
                      @selector(hook_hardwareString));
    });
}

- (id) hook_returnDeviceInfoDic {
    id res = [self hook_returnDeviceInfoDic];
    post(res, @"ATDeviceInfo-hook-returnDeviceInfoDic");
    return  res;
}

- (NSString *) hook_model {
    NSString *res = [self hook_model];
    post(res, @"ATDeviceInfo-hook-model");
    return  res;
}

- (NSString *) hook_hardwareString {
    NSString *res = [self hook_hardwareString];
    post(res, @"ATDeviceInfo-hook-hardwareString");
    return  res;
}

@end


@interface ATUtilities : NSObject
+ (NSInteger) ATTStatus;
+ (id) model;
+ (id) machine;
@end


@implementation ATUtilities (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATDeviceInfo");
        swizzleClassMethod([self class],
                      @selector(ATTStatus),
                      @selector(hook_ATTStatus));
        
        swizzleClassMethod([self class],
                      @selector(model),
                      @selector(hook_model));
        swizzleClassMethod([self class],
                      @selector(machine),
                      @selector(hook_machine));
    });
}

+ (NSInteger) hook_ATTStatus {
    NSInteger res = [self hook_ATTStatus];
    post([NSString stringWithFormat:@"%ld", res], @"ATUtilities-hook-ATTStatus");
    return  res;
}

+ (id) hook_model {
    id res = [self hook_model];
    // 打印调用堆栈
    [CallStackHelper printDetailedCallStack];
    post(res, @"ATUtilities-hook-model");
    return  res;
}
+ (id) hook_machine {
    id res = [self hook_machine];
    // 打印调用堆栈
    [CallStackHelper printDetailedCallStack];
    post(res, @"ATUtilities-hook-machine");
    return  res;
}

@end


@interface ATDeviceHandler : NSObject
+ (NSInteger) getAdvTrackingStatus;
@end


@implementation ATDeviceHandler (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATDeviceInfo");
        swizzleClassMethod([self class],
                      @selector(getAdvTrackingStatus),
                      @selector(hook_getAdvTrackingStatus));
        

    });
}

+ (NSInteger) hook_getAdvTrackingStatus {
    NSInteger res = [self hook_getAdvTrackingStatus];
    post([NSString stringWithFormat:@"%ld", res], @"ATDeviceHandler-hook-getAdvTrackingStatus");
    return  res;
}


@end

@interface MTGDeviceHandler  : NSObject
+ (NSInteger) getAdvTrackingStatus;
@end


@implementation MTGDeviceHandler  (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATDeviceInfo");
        swizzleClassMethod([self class],
                      @selector(getAdvTrackingStatus),
                      @selector(hook_getAdvTrackingStatus));
        

    });
}

+ (NSInteger) hook_getAdvTrackingStatus {
    NSInteger res = [self hook_getAdvTrackingStatus];
    post([NSString stringWithFormat:@"%ld", res], @"MTGDeviceHandler -hook-getAdvTrackingStatus");
    return  res;
}


@end


@interface MTGAFHTTPBodyPart : NSObject

- (void) setBody:(id) body;

@end


@implementation MTGAFHTTPBodyPart (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP MTGAFHTTPBodyPart");
        swizzleMethod([self class],
                      @selector(setBody:),
                      @selector(hook_setBody:));
        
    });
}

- (void) hook_setBody:(id) body {
    [self hook_setBody:body];
    post(body, @"MTGAFHTTPBodyPart-hook-setBody");
}

@end


@interface ATTAdManager : NSObject
- (void) setAdRequest:(id) request;
- (void) setAdRequestMaps:(id) request;
@end


@implementation ATTAdManager (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP MTGAFHTTPBodyPart");
        swizzleMethod([self class],
                      @selector(setAdRequest:),
                      @selector(hook_setAdRequest:));
        swizzleMethod([self class],
                      @selector(setAdRequestMaps:),
                      @selector(hook_setAdRequestMaps:));
        
    });
}

- (void) hook_setAdRequest:(id) request {
    [self hook_setAdRequest:request];
    post(request, @"ATTAdManager-hook-setAdRequest");
}

- (void) hook_setAdRequestMaps:(id) request {
    [self hook_setAdRequestMaps:request];
    post(request, @"ATTAdManager-hook-setAdRequestMaps");
}

@end


@interface ATBaseBridgeWebView : NSObject
- (void) setRequest:(id) request;
@end


@implementation ATBaseBridgeWebView (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP MTGAFHTTPBodyPart");
        swizzleMethod([self class],
                      @selector(setRequest:),
                      @selector(hook_setRequest:));
        
    });
}

- (void) hook_setRequest:(id) request {
    [self hook_setRequest:request];
    post(request, @"ATBaseBridgeWebView-hook-setRequest");
}


@end


@interface ATURLResolver : NSObject
- (void) setCurrentRequest:(id) request;
@end


@implementation ATURLResolver (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP MTGAFHTTPBodyPart");
        swizzleMethod([self class],
                      @selector(setCurrentRequest:),
                      @selector(hook_setCurrentRequest:));
        
    });
}

- (void) hook_setCurrentRequest:(id) request {
    [self hook_setCurrentRequest:request];
    post(request, @"ATURLResolver-hook-setCurrentRequest");
}


@end


@interface ATAgentEvent : NSObject
- (void) uploadData:(id) data completion:(id) completion;
@end


@implementation ATAgentEvent (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATAgentEvent");
        swizzleMethod([self class],
                      @selector(uploadData:completion:),
                      @selector(hook_uploadData:completion:));
        
    });
}

- (void) hook_uploadData:(id) data completion:(id) completion {
    [self hook_uploadData:data completion:completion];
    post(data, @"ATAgentEvent-hook-hook_uploadData");
}


@end
 


@interface ATURLArgumentModel : NSObject
- (void) setP_argumentDic:(id) data;
- (void) setP2_argumentDic:(id) data;
@end

@implementation ATURLArgumentModel (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATURLArgumentModel");
        swizzleMethod([self class],
                      @selector(setP_argumentDic:),
                      @selector(hook_setP_argumentDic:));
        
        swizzleMethod([self class],
                      @selector(setP2_argumentDic:),
                      @selector(hook_setP2_argumentDic:));
        
    });
}

- (void) hook_setP_argumentDic:(id) data {
    [self hook_setP_argumentDic:data];
    post(data, @"ATURLArgumentModel-hook_setP_argumentDic");
}
- (void) hook_setP2_argumentDic:(id) data {
    [self hook_setP2_argumentDic:data];
    post(data, @"ATURLArgumentModel-hook_setP2_argumentDic");
}

@end

@interface ATURLArgumentModule : NSObject
+ (id) getParametersWithPlacementModel:(id)placementModel parameterType:(UInt64) parameterType;
@end

@implementation ATURLArgumentModule (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATURLArgumentModule");
        swizzleClassMethod([self class],
                           @selector(getParametersWithPlacementModel:parameterType:),
                           @selector(hook_getParametersWithPlacementModel:parameterType:));
        
    });
}

+ (id) hook_getParametersWithPlacementModel:(id)placementModel parameterType:(UInt64) parameterType{
    id data = [self hook_getParametersWithPlacementModel:placementModel parameterType:parameterType];
    post(data, @"ATURLArgumentModule-hook_getParametersWithPlacementModel");
    return data;
}


@end





@implementation ATTracker (Hook)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"HOOK APP ATTracker");
        swizzleClassMethod([self class],
                           @selector(sendData:address:retryIfTimeout:),
                           @selector(hook_sendData:address:retryIfTimeout:));
        

    });
}

+ (void) hook_sendData:(id) data address:(id) address retryIfTimeout:(bool) retryIfTimeout {
    NSLog(@"hook_sendData url:%@",address);
    [self hook_sendData:data address:address retryIfTimeout:retryIfTimeout];
    post(data, @"ATTracker-hook-sendData");
}


@end


 */
