//
//  BsNetworkStatusManager.swift
//  BaiSiSMApp
//
//  Created by davidhuang on 2022/11/8.
//  Copyright © 2022 www.davidhuang.com. All rights reserved.
//

import UIKit
import Reachability

//网络状况 检测
class YHNetworkStatusManager {
    static let shared = YHNetworkStatusManager()
    var reachability: Reachability!
    init(){
        do {
            reachability = try Reachability()
            
            reachability.whenReachable = { reachability in
#if DEBUG
                if reachability.connection == .wifi {
                    print("Reachable via WiFi2")
                    YHHUD.flash(message: "当前网络: wifi")
                } else {
                    print("Reachable via Cellular")
                    YHHUD.flash(message: "当前网络: Cellular")
                }
#endif
            }
            reachability.whenUnreachable = { _ in
                print("Not reachable")
#if DEBUG
                YHHUD.flash(message: "当前网络不可用")
#endif
                
            }
        } catch {
            print("Unable to create Reachability")
            return
        }
    }
    
    var isNetWorkOK : Bool {
        if reachability.connection != .unavailable {
            return true
        } else {
            print("网络连接：不可用")
            return false
            
        }
    }
    
    var netType : Reachability.Connection {
        return reachability.connection
    }
    
    
    
    
    func listenNetWorkStatus() {
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
        do{
            try reachability.startNotifier()
        }catch{
            print("could not start reachability notifier")
        }
    }
    
    
    @objc func reachabilityChanged(note: Notification) {
        switch reachability.connection {
        case .wifi:
            print("Reachable via WiFi1")
        case .cellular:
            print("Reachable via Cellular")
        case .unavailable:
            print("Network not reachable")
        case .none:
            print(".none")
        }
    }
}
