//
//  LuxADSSModeVC.m
//  TallPaper
//
//  Created by aaa on 2024/7/26.
//

#import "LuxADSSModeVC.h"
#import "LuxNetManager.h"
#import "LuxADManager.h"
#import "RSSwizzle.h"
@interface LuxADSSButton : UIButton
@property (nonatomic,strong) LuxADManagerInterstitialItem *item;
@property (nonatomic) NSInteger clickCount;
- (void)setADItem:(LuxADManagerInterstitialItem *)item;
@property (nonatomic,strong) NSTimer *checkTimer;
@end

@implementation LuxADSSButton

- (void)setADItem:(LuxADManagerInterstitialItem *)item {
    _clickCount = 0;
    _item = item;
    self.backgroundColor = item.adItem.isReady ? [UIColor blueColor] : [UIColor orangeColor];
    _checkTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIsReady) userInfo:nil repeats:YES];
}

- (void)setClickCount:(NSInteger)clickCount{
    _clickCount = clickCount;
    [self setTitle:[NSString stringWithFormat:@"ID:%@    CN:%ld",_item.adItem.adUnitIdentifier,(long)_clickCount] forState:UIControlStateNormal];
}

- (void)dealloc {
    [_checkTimer invalidate];
    _checkTimer = nil;
}

- (void)checkIsReady {
    self.backgroundColor = _item.adItem.isReady ? [UIColor blueColor] : [UIColor orangeColor];
}
@end


@interface ZZHInfoTableViewCell : UITableViewCell
@property (nonatomic,strong) UILabel *zTitleLabel;
@property (nonatomic,strong) UILabel *zValueLabel;
@end

@implementation ZZHInfoTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _zTitleLabel = [UILabel new];
        _zValueLabel = [UILabel new];
        [self.contentView addSubview:_zTitleLabel];
        [self.contentView addSubview:_zValueLabel];
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        _zTitleLabel.frame = CGRectMake(12, 10, width-24, 20);
        _zValueLabel.frame = CGRectMake(12, 20, width-24, 90);
        _zValueLabel.numberOfLines = 0;
        
        _zTitleLabel.textColor = [UIColor orangeColor];
        _zValueLabel.textColor = [UIColor blackColor];
        
    }
    return self;
}

@end


@interface LuxADSSModeVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITextView *adInfoTextView;
@property (nonatomic,strong) UITextView *actionTextView;

@property (nonatomic,strong) UITableView *infoTableView;
@property (nonatomic,strong) NSMutableArray *dataArr;
@end





@implementation LuxADSSModeVC

+ (void)load {
    [LuxADSSModeVC ALTaskRepeatRequest_sendurl];
    
    NSLog(@"dd:%@",[NSBundle mainBundle].bundlePath);
    
}

+ (void)ALTaskRepeatRequest_sendurl {
    SEL selector = @selector(initWithRequest:delegate:sdk:);
    static const void *key = &key;
    RSSwizzleInstanceMethod([NSClassFromString(@"ALTaskRepeatRequest") class],
                            selector,
                            RSSWReturnType(id),
                            RSSWArguments(id arg1,id arg2,id arg3),
                            RSSWReplacement(
    {
        NSLog(@"ALTaskRepeatRequest arg1:\n%@",arg1);
        id body = [arg1 valueForKeyPath:@"body"];
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:body];
        NSDictionary *app_info = mdic[@"app_info"];
        NSDictionary *device_info = mdic[@"device_info"];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kreceiveAppInfo" object:nil userInfo:app_info];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"kreceiveDeviceInfo" object:nil userInfo:device_info];
        });
        
       return RSSWCallOriginal(arg1,arg2,arg3);
    }), RSSwizzleModeOncePerClass, key);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
   
}

- (void)initDataArr {
    NSMutableArray *mDeviceInfo = [NSMutableArray new];
    NSMutableArray *mAppInfo = [NSMutableArray new];
    NSMutableArray *mapplovinInfo = [NSMutableArray new];
    
    [_dataArr addObject:mDeviceInfo];
    [_dataArr addObject:mAppInfo];
    [_dataArr addObject:mapplovinInfo];
    
    NSArray *deviceInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"kzzhDeviceInfo"];
    NSArray *appInfo = [[NSUserDefaults standardUserDefaults] objectForKey:@"appInfo"];
    NSArray *applovinInfo = nil;// [[NSUserDefaults standardUserDefaults] objectForKey:@"applovinInfo"];
    
    [deviceInfo enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:obj];
        [mDeviceInfo addObject:mdic];
    }];
    
    [appInfo enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:obj];
        [mAppInfo addObject:mdic];
    }];
    
    [applovinInfo enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *mdic = [NSMutableDictionary dictionaryWithDictionary:obj];
        [mapplovinInfo addObject:mdic];
    }];
    
    [_infoTableView reloadData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSDictionary *applovinDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"com.applovin.sdk.HXOh"];
        NSLog(@"applovin dic:%@",applovinDic);
        if (applovinDic) {
            if (applovinDic[@"device_token"]) {
                [self loadApplovinInfo:@{@"device_id":applovinDic[@"device_id"],@"device_token":applovinDic[@"device_token"]}];
            }
            else if(applovinDic[@"device_id"]) {
                [self loadApplovinInfo:@{@"device_id":applovinDic[@"device_id"]}];
            }
            
        }
        else {
            NSLog(@"暂时未获取到applovindic...");
        }
    });
    
    
}

- (void)receiveDeviceInfo:(NSNotification *) note{
    NSLog(@"收到通知....");
    NSDictionary *dic = note.userInfo;
    NSMutableArray *mDeviceInfo = self.dataArr.firstObject;
    [dic.allKeys enumerateObjectsUsingBlock:^(id  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title=%@",key];
        NSMutableDictionary *mdic = [mDeviceInfo filteredArrayUsingPredicate:predicate].firstObject;
        if (!mdic) {
            mdic = [NSMutableDictionary new];
            [mdic setObject:key forKey:@"title"];
            [mDeviceInfo addObject:mdic];
        }
        
        if (![mdic valueForKey:@"value"]) {
            [mdic setObject:@(0) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
        else if (![[NSString stringWithFormat:@"%@",[mdic valueForKey:@"value"]]  isEqualToString:[NSString stringWithFormat:@"%@",[dic valueForKey:key]]]) {
            NSLog(@"receiveDeviceInfo mdic value:%@",[mdic valueForKey:@"value"] );
            NSLog(@"receiveDeviceInfo dic value:%@",[dic valueForKey:key] );
            NSInteger count = [[mdic valueForKey:@"count"] integerValue];
            [mdic setObject:@(count + 1) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
        
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:mDeviceInfo forKey:@"kzzhDeviceInfo"];
    [_infoTableView reloadData];
}

- (void)receiveAppInfo:(NSNotification *)note {
    NSDictionary *dic = note.userInfo;
    NSLog(@"receiveAppInfo:%@",dic);
    NSMutableArray *mAppInfo = self.dataArr[1];
    [dic.allKeys enumerateObjectsUsingBlock:^(id  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title=%@",key];
        NSMutableDictionary *mdic = [mAppInfo filteredArrayUsingPredicate:predicate].firstObject;
        if (!mdic) {
            mdic = [NSMutableDictionary new];
            [mdic setObject:key forKey:@"title"];
            [mAppInfo addObject:mdic];
        }
        
        if (![mdic valueForKey:@"value"]) {
            [mdic setObject:@(0) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
        else if (![[NSString stringWithFormat:@"%@",[mdic valueForKey:@"value"]]  isEqualToString:[NSString stringWithFormat:@"%@",[dic valueForKey:key]]]) {
            NSLog(@"mdic value:%@",[mdic valueForKey:@"value"] );
            NSLog(@"dic value:%@",[dic valueForKey:key] );
            NSInteger count = [[mdic valueForKey:@"count"] integerValue];
            [mdic setObject:@(count + 1) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
       
        
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:mAppInfo forKey:@"appInfo"];
    [_infoTableView reloadData];
}

- (void)loadApplovinInfo:(NSDictionary *)dic {
    NSLog(@"receiveAppInfo:%@",dic);
    NSMutableArray *mAppInfo = self.dataArr[2];
    [dic.allKeys enumerateObjectsUsingBlock:^(id  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title=%@",key];
        NSMutableDictionary *mdic = [mAppInfo filteredArrayUsingPredicate:predicate].firstObject;
        if (!mdic) {
            mdic = [NSMutableDictionary new];
            [mdic setObject:key forKey:@"title"];
            [mAppInfo addObject:mdic];
        }
        
        if (![mdic valueForKey:@"value"]) {
            [mdic setObject:@(0) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
        else if (![[NSString stringWithFormat:@"%@",[mdic valueForKey:@"value"]]  isEqualToString:[NSString stringWithFormat:@"%@",[dic valueForKey:key]]]) {
            NSLog(@"mdic value:%@",[mdic valueForKey:@"value"] );
            NSLog(@"dic value:%@",[dic valueForKey:key] );
            NSInteger count = [[mdic valueForKey:@"count"] integerValue];
            [mdic setObject:@(count + 1) forKey:@"count"];
            [mdic setObject:[dic valueForKey:key] forKey:@"value"];
        }
       
        
    }];
    
    [[NSUserDefaults standardUserDefaults] setObject:mAppInfo forKey:@"applovinInfo"];
    [_infoTableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataArr = [NSMutableArray new];
    [self initDataArr];
//    self.view.backgroundColor = [UIColor redColor];
    self.navigationController.navigationBarHidden = YES;
    __block CGFloat currY = 50.0;
    CGFloat cellHeight = 50;
    CGFloat cellPadding = 20;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    
    CGFloat cellWidth = (screenW - cellPadding*2);
    
    [[[LuxADManager shareInstance] allInterstitialAds] enumerateObjectsUsingBlock:^(LuxADManagerInterstitialItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGRect rect = CGRectMake(cellPadding, currY, cellWidth, cellHeight);
        LuxADSSButton *button = [LuxADSSButton new];
        [button setADItem:obj];
        button.frame = rect;
        button.tag = idx + 1;
        obj.tapPointX = @(button.center.x);
        obj.tapPointY = @(button.center.y);
        [button addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitle:[NSString stringWithFormat:@"ID: %@",obj.adItem.adUnitIdentifier] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:18];
        button.backgroundColor = [UIColor orangeColor];
        
        [self.view addSubview:button];
        currY += cellPadding + cellHeight;
        
    }];
    
    _adInfoTextView = [UITextView new];
    _adInfoTextView.frame = CGRectMake(0, currY, screenW*0.5, screenH - currY);
    [self.view addSubview:_adInfoTextView];
    _adInfoTextView.backgroundColor = [UIColor purpleColor];
    _adInfoTextView.editable = NO;
    _adInfoTextView.textColor = [UIColor whiteColor];
    _adInfoTextView.font = [UIFont systemFontOfSize:14];
    _adInfoTextView.layoutManager.allowsNonContiguousLayout = NO;
    
    _actionTextView = [UITextView new];
    _actionTextView.frame = CGRectMake(screenW - _adInfoTextView.frame.size.width, _adInfoTextView.frame.origin.y, _adInfoTextView.frame.size.width, _adInfoTextView.frame.size.height);
    [self.view addSubview:_actionTextView];
    _actionTextView.backgroundColor = [UIColor lightGrayColor];
    _actionTextView.editable = NO;
    _actionTextView.textColor = [UIColor whiteColor];
    _actionTextView.font = [UIFont systemFontOfSize:14];
    _actionTextView.layoutManager.allowsNonContiguousLayout = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adInfoNtification:) name:kLuxADSSModeVC_Notification_AdInfo object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionInfoNtification:) name:kLuxADSSModeVC_Notification_ActionInfo object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveDeviceInfo:) name:@"kreceiveDeviceInfo" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveAppInfo:) name:@"kreceiveAppInfo" object:nil];
    _infoTableView = [[UITableView alloc] init];
    [self.view addSubview:_infoTableView];
    _infoTableView.frame = self.view.bounds;
    _infoTableView.backgroundColor = [UIColor purpleColor];
    _infoTableView.delegate = self;
    _infoTableView.dataSource = self;
    [_infoTableView registerClass:[ZZHInfoTableViewCell class] forCellReuseIdentifier:@"kZZHInfoTableViewCell"];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)clickAction:(LuxADSSButton *)sender {
    sender.item.actionBlock(self);
    sender.clickCount += 1;
    NSLog(@"rect:%@",NSStringFromCGRect(sender.frame));
}

- (void)actionInfoNtification:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *info = notification.userInfo[@"info"];
        NSString *text = _actionTextView.text ?  _actionTextView.text : @"";
        text = [text stringByAppendingFormat:@"\n\n%@",info];
        _actionTextView.text = text;

        [_actionTextView scrollRangeToVisible:NSMakeRange(_actionTextView.text.length, 1)];
    });
}

- (void)adInfoNtification:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *info = notification.userInfo[@"info"];
        NSString *text = _adInfoTextView.text ?  _adInfoTextView.text : @"";
        text = [text stringByAppendingFormat:@"\n\n%@",info];
        _adInfoTextView.text = text;
        [_adInfoTextView scrollRangeToVisible:NSMakeRange(_actionTextView.text.length, 1)];
    });
    
}

- (void)textViewScrollToBottom:(UITextView *)textView {
    NSLog(@"the info:%@",textView.text);
    
    CGFloat bottomOffset = textView.contentSize.height - textView.bounds.size.height;
    NSLog(@"the %@, bound:\n%@",NSStringFromCGSize(textView.contentSize),NSStringFromCGSize(textView.bounds.size));
    if (bottomOffset > 0) {
        [textView setContentOffset:CGPointMake(0, bottomOffset)];
    }
}


#pragma mark ---tableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.dataArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArr[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZZHInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kZZHInfoTableViewCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[ZZHInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"kZZHInfoTableViewCell"];
    }
    NSDictionary *dic = self.dataArr[indexPath.section][indexPath.row];
    cell.zTitleLabel.text = [NSString stringWithFormat:@"%@     变更次数:%@",dic[@"title"],dic[@"count"]];
    cell.zValueLabel.text = [NSString stringWithFormat:@"%@",dic[@"value"]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return  50;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *headerLabel = [UILabel new];
    if (section == 0) {
        headerLabel.text = @"     设备信息" ;
    }
    else if (section == 1) {
        headerLabel.text = @"    App Info";
    }
    else {
        headerLabel.text = @"    AppLovin SDK Info";
    }
    
    headerLabel.frame = CGRectMake(0, 0, 200, 30);
    headerLabel.backgroundColor = [UIColor systemPurpleColor];
    return  headerLabel;
}
@end




