//
//  ipManager.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/6/4.
//

import Foundation
import UIKit
import SystemConfiguration
import Foundation

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
    
    
    
    private override init() {}
    
    
}

///本地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()
}






