//
//  ip+idfa.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/11.
//

import Foundation
import UIKit
import AdSupport
import AppTrackingTransparency
import SystemConfiguration
import Alamofire
class StartManager:NSObject{
    static var shared = StartManager()
    
    ///本地ip
    var localIP:String?
    ///远程ip
    var publicIP:String?
    ///设备ID
    var devicID:String?
    ///IDFA
    var idfaid:String?
    ///货架号
    var shelfNumber:String?
    ///包名
    var packageName:String = "com.wallpapaer.hd.live.app"
    ///广告加载是否成功
    var succeed:Bool = false
    ///加载时间
    var loadTime:Int?
    ///广告平台
    var adPlatform:String?
    ///国家代码
    var countryCode:String?
    ///广告Id
    var adId:String?
    ///平台广告响应时间
    var platformResponseTime:TimeInterval?
    ///获取IP响应时间
    var getIpResponseTime:Float?
    ///广告单价
    var ecpm:Float?
    ///广告售卖平台1
    var dsp:String?
    ///广告售卖平台2
    var network:String?
    ///superHero
    var superHero:Bool = false
    
    
    /// bee9f7039e56cc7a
    var idOneprice:Float?
    var idOneAD:String = "bee9f7039e56cc7a"
    var idOnex:CGFloat = UIScreen.main.bounds.width / 2
    var idOney:CGFloat = 20
    
    /// 8fccdfa964b52e26
    var idTwoprice:Float?
    var idTwoAD:String = "8fccdfa964b52e26"
    var idTwox:CGFloat = UIScreen.main.bounds.width / 2
    var idTwoy:CGFloat = 65
    
    /// bee9f7039e56cc7a
    var idThreeprice:Float?
    var idThreeAD:String = "7baed02646413e44"
    var idThreex:CGFloat = UIScreen.main.bounds.width / 2
    var idThreey:CGFloat = 110
    
    
    ///IDADtype
    var IDADType:Int = 1
    
    
    let loadurl = "http://127.0.0.1:6000/adtask/loaded"
    
    let showurl = "http://127.0.0.1:6000/adtask/show"
    
    let closedUrl = "http://127.0.0.1:6000/adtask/closed"
    
    let headers: HTTPHeaders = [
        "Content-Type": "application/json"
    ]
    
    private override init() {}
    
    
}

let strings = ["bee9f7039e56cc7a", "8fccdfa964b52e26", "7baed02646413e44","2e66a808a4251e3a"]

func getRandomString() -> String? {
    return strings.randomElement()
}

///本地ip
func getLocalIPAddress() -> String? {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil

    if getifaddrs(&ifaddr) == 0 {
        var ptr = ifaddr
        while ptr != nil {
            let interface = ptr?.pointee
            let addrFamily = interface?.ifa_addr.pointee.sa_family

            if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                if let name = interface?.ifa_name, String(cString: name) == "en0" {
                    var addr = interface?.ifa_addr.pointee
                    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                    if getnameinfo(&addr!, socklen_t((interface?.ifa_addr.pointee.sa_len)!),
                                   &hostname, socklen_t(hostname.count),
                                   nil, socklen_t(0), NI_NUMERICHOST) == 0 {
                        address = String(cString: hostname)
                    }
                }
            }
            ptr = interface?.ifa_next
        }
        freeifaddrs(ifaddr)
    }
    return address
}
///远程ip
func getPublicIPAddress(completion: @escaping (String?) -> Void) {
    let url = URL(string: "https://api.ipify.org?format=json")!
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            print("Error fetching public IP address: \(error?.localizedDescription ?? "Unknown error")")
            completion(nil)
            return
        }
        
        if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
           let ip = json["ip"] as? String {
            completion(ip)
        } else {
            completion(nil)
        }
    }
    
    task.resume()
}


func requestTrackingAuthorization(completion: @escaping (String?) -> Void) {
    if #available(iOS 14, *) {
        var attemptsLeft = 3
        
        func requestAuth() {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                    print("Authorized: IDFA = \(idfa)")
                    completion(idfa)
                case .denied, .restricted:
                    print("Denied or Restricted")
                    completion(nil)
                case .notDetermined:
                    print("Not Determined")
                    attemptsLeft -= 1
                    if attemptsLeft > 0 {
                        requestAuth() // 继续请求直到达到最大尝试次数
                    } else {
                        print("Reached maximum number of attempts")
                        completion(nil)
                    }
                @unknown default:
                    print("Unknown status")
                    completion(nil)
                }
            }
        }
        
        requestAuth() // 第一次请求
    } else {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            print("Tracking enabled: IDFA = \(idfa)")
            completion(idfa)
        } else {
            print("Tracking not enabled")
            completion(nil)
        }
    }
}



func requestIDFA(completion: @escaping (String?) -> Void) {
    if #available(iOS 14, *) {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                completion(idfa)
            default:
                completion(nil)
            }
        }
    } else {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            completion(idfa)
        } else {
            completion(nil)
        }
    }
}

