//
//  MPNetWorkManager.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/4/11.
//

import UIKit
import Network
///网络状况管理器
class MPNetWorkManager: NSObject {
    //单例工具
    static let shared = MPNetWorkManager()
    //私有初始化
    private override init() {
        super.init()
    }
    ///检查网络状况
    func requestNetworkPermission(oberve:UIViewController, completeHanlder:ActionBlock?) {
        let monitor = NWPathMonitor()
        monitor.pathUpdateHandler = { path in
            switch path.status {
            case .satisfied:
                DispatchQueue.main.async {
                    guard completeHanlder != nil else {
                        return
                    }
                    completeHanlder!()
                }
            default://网络权限出现问题
                DispatchQueue.main.async {
                    //次要处理
                    let alertController = UIAlertController(title: "Access network request", message: "”Musicoo“ needs to be loaded via a network request. Please click “Settings” to allow this application to gain access to the network.", preferredStyle: .alert)
                    let CancelAction = UIAlertAction(title:"Cancel", style: .cancel) { (Cancel) in

                    }
                    let OKAction = UIAlertAction(title: "Settings", style: .default) { (action) in
                        let url = URL(string: UIApplication.openSettingsURLString)
                        if let url = url,UIApplication.shared.canOpenURL(url){
                            if #available(iOS 10, *) {
                                UIApplication.shared.open(url, options: [:]) { (success) in
                                }
                            }else{
                                UIApplication.shared.canOpenURL(url)
                            }
                        }
                    }
                    alertController.addAction(CancelAction)
                    alertController.addAction(OKAction)
                    oberve.present(alertController, animated: true, completion: nil)
                }
            }
        }
        let queue = DispatchQueue(label: "MPNetWorkManager")
        monitor.start(queue: queue)
    }
}
