//
//  NetManager.m
//  HD wallpaper
//
//  Created by aaa on 2024/7/4.
//

#import "AWM_NetManager.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 @"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"

@implementation AWM_NetManager

+ (void)uploadData:(NSMutableDictionary *)mdic urlPath:(NSString *)urlPath callback:(NetManagerCallback)callback {
    NSURL *url = [NSURL URLWithString:kUrlStr(urlPath)];
    if (!url) {
        NSLog(@"Invalid URL: %@", kUrlStr(urlPath));
        return;
    }
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    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) {
            NSLog(@"Network error: %@", error.localizedDescription);
        } else {
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            NSLog(@"HTTP Status Code: %ld", (long)httpResponse.statusCode);
            if (data) {
                NSError *jsonParseError;
                NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonParseError];
                if (jsonParseError) {
                    NSLog(@"Error parsing response JSON: %@", jsonParseError.localizedDescription);
                } else {
                    NSLog(@"Server response: %@", result);
                    if (callback) {
                        callback(nil, YES, result);
                    }
                }
            } else {
                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:@"com.trendwallpaper.app" forKey:@"packageName"];
    [mdic setObject:@"" forKey:@"linkId"];
    [mdic setObject:@"" forKey:@"dataId"];
    
    [AWM_NetManager uploadData:mdic urlPath:kURL_AD_Start callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        
    }];
}

+ (void)uploadAD_Show {
    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:@"com.trendwallpaper.app" forKey:@"packageName"];
       [mdic setObject:@"MAX" forKey:@"adPlatform"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"countryCode"] forKey:@"countryCode"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"adId"] forKey:@"adId"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"platformResponseTime"] forKey:@"platformResponseTime"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"shelfNumber"] forKey:@"shelfNumber"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ecpm"] forKey:@"ecpm"];
       [mdic setObject:@0.0 forKey:@"getIpResponseTime"];
       [mdic setObject:@"" forKey:@"dsp"];
       [mdic setObject:@"" forKey:@"dataId"];
       [mdic setObject:@"" forKey:@"linkId"];
       [mdic setObject:@0 forKey:@"loadTime"];
       [mdic setObject:@(YES) forKey:@"succeed"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"network"] 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);
    
    [AWM_NetManager uploadData:mdic urlPath: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 {
    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:@"com.trendwallpaper.app" forKey:@"packageName"];
       [mdic setObject:@"MAX" forKey:@"adPlatform"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"countryCode"] forKey:@"countryCode"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"adId"] forKey:@"adId"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"platformResponseTime"] forKey:@"platformResponseTime"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"shelfNumber"] forKey:@"shelfNumber"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ecpm"] forKey:@"ecpm"];
       [mdic setObject:@0.0 forKey:@"getIpResponseTime"];
       [mdic setObject:@"" forKey:@"dsp"];
       [mdic setObject:@"" forKey:@"dataId"];
       [mdic setObject:@"" forKey:@"linkId"];
       [mdic setObject:@0 forKey:@"loadTime"];
       [mdic setObject:@(YES) forKey:@"succeed"];
       [mdic setObject:[[NSUserDefaults standardUserDefaults] stringForKey:@"network"] 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);
    
    [AWM_NetManager uploadData:mdic urlPath:kURL_AD_Load callback:^(NSError * _Nonnull err, BOOL state, NSDictionary * _Nonnull result) {
        if (err) {
                  NSLog(@"222222222: %@", err.localizedDescription);
              } else {
                  NSLog(@"222222222222: %@", result);
              }
    }];
}

//请求远程ip
+ (void)requestRemoteIp {
    NSURL *url = [NSURL URLWithString:@"https://api.ipify.org/?format=json"];
    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失败....");
        }
        else {
            id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if(result) {
                NSString *ip = result[@"ip"];
                if(ip.length) {
                    [[NSUserDefaults standardUserDefaults] setObject:ip forKey:@"kIP_key"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                }
                else {
                    NSLog(@"解析ip失败....");
                }
            }
            else {
                NSLog(@"解析ip失败....");
            }
        }
    }];
    [task resume];
}

+ (NSString *)getDeviceId {
    return [UIDevice currentDevice].identifierForVendor.UUIDString;
}


+ (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) {
        
NSInteger bravery_T = 6;
NSInteger awful_q = [[NSUserDefaults standardUserDefaults] integerForKey:@"trademark_e"];
awful_q *= bravery_T;
[[NSUserDefaults standardUserDefaults] setInteger:awful_q forKey:@"trademark_e"];


                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
        
NSDateFormatter *rebuke_5 = [NSDateFormatter new];
[rebuke_5 setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *apple_5 = [rebuke_5 stringFromDate:[NSDate date]];
[[NSUserDefaults standardUserDefaults] setObject:apple_5 forKey:@"brutal_f"];


                    // 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;
}



@end
