//
//  LTNetwork.swift
//  LegendTeam
//
//  Created by dong on 2022/1/16.
//

import Alamofire
import Foundation

enum ReachabilityStatus {
    case notReachable
    case unknown
    case ethernetOrWiFi
    case wwan
}

class LTNetworkManage {
    static let ltManage = LTNetworkManage()
    private(set) var status: ReachabilityStatus = .unknown
    let manager = NetworkReachabilityManager()
    
    // 新增：跟踪是否已经发送过网络恢复通知
    private var hasNotifiedNetworkRestored = false
    
    var reachable: Bool{
        return status != .notReachable
    }
    
    func netWorkReachability(reachabilityStatus: ((ReachabilityStatus) -> Void)?) {
        
        manager!.startListening { status in
            let beforeStatus = LTNetworkManage.ltManage.status
            // wifi
            if status == NetworkReachabilityManager.NetworkReachabilityStatus.reachable(.ethernetOrWiFi) {
                print("☁️------.wifi")
                LTNetworkManage.ltManage.status = .ethernetOrWiFi
                reachabilityStatus?(.ethernetOrWiFi)
                
                // 检查是否从无网状态恢复到有网状态
                if beforeStatus == .notReachable && !LTNetworkManage.ltManage.hasNotifiedNetworkRestored {
                    LTNetworkManage.ltManage.hasNotifiedNetworkRestored = true
                    NotificationCenter.post(name: .networkRestored, object: nil, userInfo: nil)
                }
            }
            // 不可用
            if status == NetworkReachabilityManager.NetworkReachabilityStatus.notReachable {
                print("☁️------没网")
                LTNetworkManage.ltManage.status = .notReachable
                reachabilityStatus?(.notReachable)
                
                // 重置通知标志，以便下次网络恢复时可以再次通知
                LTNetworkManage.ltManage.hasNotifiedNetworkRestored = false
            }
            // 未知
            if status == NetworkReachabilityManager.NetworkReachabilityStatus.unknown {
                print("☁️------未知")
                LTNetworkManage.ltManage.status = .unknown
                reachabilityStatus?(.unknown)
            }

            // 蜂窝
            if status == NetworkReachabilityManager.NetworkReachabilityStatus.reachable(.cellular) {
                print("☁️------蜂窝")
                LTNetworkManage.ltManage.status = .wwan
                reachabilityStatus?(.wwan)
                
                // 检查是否从无网状态恢复到有网状态
                if beforeStatus == .notReachable && !LTNetworkManage.ltManage.hasNotifiedNetworkRestored {
                    LTNetworkManage.ltManage.hasNotifiedNetworkRestored = true
                    NotificationCenter.post(name: .networkRestored, object: nil, userInfo: nil)
                }
            }
            if beforeStatus != .unknown, beforeStatus != LTNetworkManage.ltManage.status{
                NotificationCenter.post(name: .networkChanged, object: nil, userInfo: nil)
            }
        }
    }
}
