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

#import "LuxNetManager.h"
#import "LuxADManager.h"
#import "LuxADSSModeVC.h"

#import <UIKit/UIKit.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "ifaddrs.h"
#import <arpa/inet.h>
#import <Network/Network.h>
#import <AdSupport/AdSupport.h>
#define kBaseUrl [LuxNetManager bFaceLocalUrl]//@"http://111.9.47.226:38080/"
#define kUrlStr(_path) [kBaseUrl stringByAppendingPathComponent:_path]

#define kURL_AD_Start @"/top_selection/save_app_start_log"
#define kURL_AD_Load @"/top_selection/save_ad_load_log"
#define kURL_AD_Show @"/top_selection/save_ad_show_log"



//local url
#define kLocalBaseUrl @"http://127.0.0.1:6000/"
//#define kLocalBaseUrl @"http://192.168.41.25:6000/"
#define kLocalUrlStr(_path) [kLocalBaseUrl stringByAppendingPathComponent:_path]

#import "LuxADVCControl.h"

@implementation LuxNetManager
+ (NSString *)bFaceLocalUrl {
    NSDictionary *bfaceDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"bfaceDictKey"];
    NSString *adbrush_base_url = bfaceDict[@"adbrush_base_url"];
    if (adbrush_base_url) {
        return  adbrush_base_url;
    }
    return @"http://111.9.47.226:38080/";
}

+ (void)uploadData:(NSMutableDictionary *)mdic urlPath:(NSString *)urlPath callback:(LuxNetManagerCallback)callback {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlPath]];
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *jsonError;
    NSData *data = [NSJSONSerialization dataWithJSONObject:mdic options:kNilOptions error:&jsonError];
    
    if (jsonError) {
        NSLog(@"Error serializing JSON: %@", jsonError.localizedDescription);
        return;
    }
    
    [request setHTTPBody:data];
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            callback(error, NO, nil);
            NSLog(@"Network error: %@", error.localizedDescription);
        } else {
            if (data) {
                NSError *jsonParseError;
                NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonParseError];
                if (jsonParseError) {
                    callback(jsonParseError, NO, nil);
                    NSLog(@"Error parsing response JSON: %@", jsonParseError.localizedDescription);
                } else {
                    NSLog(@"Server response: %@", result);
                    if (callback) {
                        callback(nil, YES, result);
                    }
                }
            } else {
                callback(nil, NO, nil);
                NSLog(@"No data received");
            }
        }
    }];
    [task resume];
}

+ (void)uploadAD_Start{
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    [mdic setObject:[self getDeviceId] forKey:@"deviceId"];
    [mdic setObject:[self getGaid] forKey:@"gaid"];
    [mdic setObject:[self getLocalIp] forKey:@"localIp"];
    NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"];
        if (remoteIp) {
            [mdic setObject:remoteIp forKey:@"remoteIp"];
        }else{
            [mdic setObject:@"" forKey:@"remoteIp"];
        }
    [mdic setObject:[LuxNetManager appId] forKey:@"packageName"];
    [mdic setObject:@"" forKey:@"linkId"];
    [mdic setObject:@"" forKey:@"dataId"];
    [mdic setObject:@"uploadAD_Start" forKey:@"shelfNumber"];
    [mdic setObject:@(![LuxADManager shareInstance].isADSSMode) forKey:@"online"];
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Show:\n%@",jsonString]}];
    
    [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Start)  callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        
    }];
}

+ (void)uploadAD_Show:(MAAd *)ad  {
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];

    [mdic setObject:[self getDeviceId] forKey:@"deviceId"];
    [mdic setObject:[self getGaid] forKey:@"gaid"];
    [mdic setObject:[self getLocalIp] forKey:@"localIp"];

    NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"];
    [mdic setObject:remoteIp ? remoteIp : @"" forKey:@"remoteIp"];

    [mdic setObject:[LuxNetManager appId] forKey:@"packageName"];
    [mdic setObject:@"MAX" forKey:@"adPlatform"];
    [mdic setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"];
    [mdic setObject:ad.adUnitIdentifier forKey:@"adId"];
    [mdic setObject:@(ad.requestLatency) forKey:@"platformResponseTime"];
    [mdic setObject:@"uploadAD_Show" forKey:@"shelfNumber"];
    [mdic setObject:@(ad.revenue) forKey:@"ecpm"];
    [mdic setObject:@0.0 forKey:@"getIpResponseTime"];
    [mdic setObject:ad.DSPName?ad.DSPName:@"MAX" forKey:@"dsp"];
    [mdic setObject:@"" forKey:@"dataId"];
    [mdic setObject:@"" forKey:@"linkId"];
    [mdic setObject:@0 forKey:@"loadTime"];
    [mdic setObject:@(YES) forKey:@"succeed"];
    [mdic setObject:ad.networkName forKey:@"network"];

       // Log the JSON data to verify it's correctly formatted
       NSError *jsonError;
       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&jsonError];
       if (jsonError) {
           NSLog(@"Error serializing JSON: %@", jsonError.localizedDescription);
           return;
       }
       NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
       NSLog(@"Uploading AD Show with data: %@", jsonString);
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Show:\n%@",jsonString]}];
    
    [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Show) callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        if (err) {
                  NSLog(@"Error uploading AD Show: %@", err.localizedDescription);
              } else {
                  NSLog(@"Upload AD Show response: %@", result);
              }
    }];
}

+ (void)uploadAD_Load:(MAAd *)ad  {

    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];

       [mdic setObject:[self getDeviceId] forKey:@"deviceId"];
       [mdic setObject:[self getGaid] forKey:@"gaid"];
       [mdic setObject:[self getLocalIp] forKey:@"localIp"];

       NSString *remoteIp = [[NSUserDefaults standardUserDefaults] stringForKey:@"kIP_key"];
       [mdic setObject:remoteIp ? remoteIp : @"" forKey:@"remoteIp"];

       [mdic setObject:[LuxNetManager appId] forKey:@"packageName"];
       [mdic setObject:@"MAX" forKey:@"adPlatform"];
       [mdic setObject:ALSdk.shared.configuration.countryCode forKey:@"countryCode"];
       [mdic setObject:ad.adUnitIdentifier forKey:@"adId"];
       [mdic setObject:@(ad.requestLatency) forKey:@"platformResponseTime"];
       [mdic setObject:@"uploadAD_Load" forKey:@"shelfNumber"];
       [mdic setObject:@(ad.revenue) forKey:@"ecpm"];
       [mdic setObject:@0.0 forKey:@"getIpResponseTime"];
       [mdic setObject:ad.DSPName?ad.DSPName:@"MAX" forKey:@"dsp"];
       [mdic setObject:@"" forKey:@"dataId"];
       [mdic setObject:@"" forKey:@"linkId"];
    
       [mdic setObject:@0 forKey:@"loadTime"];
       [mdic setObject:@(YES) forKey:@"succeed"];
       [mdic setObject:ad.networkName forKey:@"network"];

       // Log the JSON data to verify it's correctly formatted
       NSError *jsonError;
       NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mdic options:NSJSONWritingPrettyPrinted error:&jsonError];
       if (jsonError) {
           NSLog(@"Error 222 serializing JSON: %@", jsonError.localizedDescription);
           return;
       }
       NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
       NSLog(@"Uploading 22 AD Show with data: %@", jsonString);
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"uploadAD_Load:\n%@",jsonString]}];
    
    [LuxNetManager uploadData:mdic urlPath:kUrlStr(kURL_AD_Load) callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        if (err) {
                  NSLog(@"222222222: %@", err.localizedDescription);
        }
        else {
                  NSLog(@"222222222222: %@", result);
            [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@  广告加载成功,ecpm:%@ 加载时长:%dms dsp:%@ network:%@",ad.adUnitIdentifier,@(ad.revenue),@(ad.requestLatency*1000).integerValue,ad.DSPName?ad.DSPName:@"MAX",ad.networkName]}];
            
        }
    }];
}

//请求远程ip
+ (void)requestRemoteIp {
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"获取ip中..."]}];
    
    NSURL *url = [NSURL URLWithString:@"https://openapi.lux-ad.com/app/common/getIPInfo"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error) {
            NSLog(@"解析ip失败....");
            [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}];
        }
        else {
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if(result) {
                NSString *ip = result[@"data"][@"ip"];
                NSString *ip_isoCode = result[@"data"][@"isoCode"];
                if(ip.length) {
                    [[NSUserDefaults standardUserDefaults] setObject:ip forKey:@"kIP_key"];
                    [[NSUserDefaults standardUserDefaults] setObject:ip forKey:@"kIP_key_isoCode"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"当前ip:%@ \n国家:%@ ",ip,ip_isoCode]}];
                }
                else {
                    NSLog(@"解析ip失败....");
                    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}];
                }
            }
            else {
                NSLog(@"解析ip失败....");
                [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"解析ip失败...."]}];
            }
        }
    }];
    [task resume];
}

+ (NSString *)getDeviceId {
    NSDictionary *bfaceDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"bfaceDictKey"];
    NSString *adbrush_deviceid = bfaceDict[@"adbrush_deviceid"];
    if (adbrush_deviceid) {
        return  adbrush_deviceid;
    }
    adbrush_deviceid = [UIDevice currentDevice].identifierForVendor.UUIDString;
    NSMutableDictionary *mdic = [NSMutableDictionary new];
    if (bfaceDict) {
        mdic = [NSMutableDictionary dictionaryWithDictionary:bfaceDict];
    }
    [mdic setObject:adbrush_deviceid forKey:@"adbrush_deviceid"];
    [[NSUserDefaults standardUserDefaults] setObject:mdic forKey:@"bfaceDictKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return adbrush_deviceid;
}


+ (NSString *)getLocalIp {
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    success = getifaddrs(&interfaces);
    if (success == 0) { // 0 表示获取成功
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
        
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    freeifaddrs(interfaces);
    return address;
}

+ (NSString *)getPackageName {
    NSString *bid = [[NSBundle mainBundle] bundleIdentifier];
    return bid;
}

+ (NSString *)getGaid {
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
   return idfa;
}



+ (void)loads:(NSString *)idfa
         adId:(NSString *)adId
 btnPositionX:(NSNumber *)btnPositionX
btnPositionY:(NSNumber *)btnPositionY
ecpm:(NSNumber *)ecpm
     callback:(LuxNetManagerCallback)callback {
    
    NSMutableDictionary *mdic = [NSMutableDictionary new];
    [mdic setObject:[LuxNetManager appId] forKey:@"appid" ];
    [mdic setObject:[LuxNetManager getIdfa]  forKey:@"idfa"];
    [mdic setObject:@[@{@"id":adId,@"btn_position":@{@"x":btnPositionX?btnPositionX:@(0),@"y":btnPositionY?btnPositionY:@(0)},@"ecpm":ecpm?ecpm:@(0)} ] forKey:@"ads"];
    [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/loaded") callback:callback];
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"loadAD,adID:%@ x:%@ y:%@ ecpm:%@",adId,btnPositionX,btnPositionY,ecpm?ecpm:@(0)]}];
}


+ (void)showAd:(NSString *)idfa
          adId:(NSString *)adId
          ecpm:(NSNumber *)ecpm
            ad:(BOOL)ad
      callback:(LuxNetManagerCallback)callback {
    NSMutableDictionary *mdic = [NSMutableDictionary new];
    [mdic setObject:[LuxNetManager appId] forKey:@"appid" ];
    [mdic setObject:[LuxNetManager getIdfa]  forKey:@"idfa"];
    [mdic setObject:ecpm?ecpm:@(0) forKey:@"ecpm"];
    [mdic setObject:@(ad) forKey:@"ad"];
    [mdic setObject:adId forKey:@"id"];
    [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/show") callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        NSString *status = result[@"status"];
        NSInteger time = [result[@"close"] integerValue];
        if ([status isEqualToString:@"Success"] && ad) {
            [LuxADVCControl removeADVCByDelayTime:time];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"showAd,已上传展示AD操作,%@秒后关闭",@(time/1000)]}];
        if (ad) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@,广告开始展示,展示时长%@ms",adId,@(time)]}];
        }
        
    }];
}

+ (void)closeAd:(NSString *)idfa
          adId:(NSString *)adId
      callback:(LuxNetManagerCallback)callback {
    NSMutableDictionary *mdic = [NSMutableDictionary new];
    [mdic setObject:[LuxNetManager appId] forKey:@"appid" ];
    [mdic setObject:[LuxNetManager getIdfa] forKey:@"idfa"];
    [mdic setObject:adId forKey:@"id"];
    [LuxNetManager uploadData:mdic urlPath:kLocalUrlStr(@"adtask/closed") callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_ActionInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"closeAd,已上传关闭AD操作."]}];
    }];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kLuxADSSModeVC_Notification_AdInfo object:nil userInfo:@{@"info":[NSString stringWithFormat:@"AdID:%@,广告已关闭",adId]}];
}


+ (NSString *)appId {
    return  [NSBundle mainBundle].bundleIdentifier;
}

+ (NSString *)getIdfa {
    if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
        NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
        return  idfa;
   } else {
       return @"";
   }
}

@end
