//
//  NetStatusManager.swift
//  PhoneManager
//
//  Created by edy on 2025/3/27.
//

import Alamofire
import Network

enum NetStatus{
    
    case NoNet
    case WIFI
    case WWAN
}


class NetStatusManager: NSObject {
    static let manager:NetStatusManager = NetStatusManager()
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "NetworkMonitorQueue")
    var currentStatus:NetStatus?
    
    func startNet(netStatus: @escaping(NetStatus)->Void) {
        
        monitor.pathUpdateHandler = { path in

            if path.status == .satisfied {
                if path.isExpensive {
                    self.currentStatus = .WWAN
                    netStatus(.WWAN)
                    
                } else {
                    
                    self.currentStatus = .WIFI
                    netStatus(.WIFI)
                    
                }
            } else {
                
                self.currentStatus = .NoNet
                netStatus(.NoNet)
            }
        }
                
        monitor.start(queue: queue)
    }
    
    func stop() {
        
        monitor.cancel()
    }
    
}


import Foundation
import SystemConfiguration.CaptiveNetwork

func getWiFiAddress() -> String? {
    var address: String?
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    
    // 获取网络接口列表
    guard getifaddrs(&ifaddr) == 0 else { return nil }
    guard let firstAddr = ifaddr else { return nil }
    
    // 遍历接口列表
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
        let interface = ifptr.pointee
        let addrFamily = interface.ifa_addr.pointee.sa_family
        
        // 检查接口是否为 IPv4 或 IPv6
        if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
            let name = String(cString: interface.ifa_name)
            
            // 筛选出 Wi-Fi (en0) 接口的 IP 地址
            if name == "en0" {
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len),
                            &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST)
                address = String(cString: hostname)
            }
        }
    }
    
    freeifaddrs(ifaddr)
    return address
}


