//
//  UIApplication+Extension.swift
//  QuickSearchLocation
//
//  Created by mac on 2024/4/10.
//

import Foundation
import UIKit

public extension UIApplication {
    
    //MARK: 1.1、获取当前的keyWindow
    /// 获取当前的keyWindow
    static var keyWindow: UIWindow? {
        if #available(iOS 13, *) {
            return UIApplication.shared.windows.filter { $0.isKeyWindow }.first
        } else {
            return UIApplication.keyWindow
        }
    }
    
    // MARK: 1.2、获取根控制器
    /// 获取根控制器
    /// - Parameter base: 哪个控制器为基准
    /// - Returns: 返回 UIViewController
    static func topViewController(_ base: UIViewController? = UIApplication.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }
        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }
        return base
    }
    
    // MARK: 1.3、网络状态是否可用
    /// 网络状态是否可用
    static func reachable() -> Bool {
        let data = NSData(contentsOf: URL(string: "https://www.baidu.com/")!)
        return (data != nil)
    }
    
}

import UIKit

extension UIApplication {
    @MainActor
    static func currentViewController() -> UIViewController? {
        var rootViewController: UIViewController?
        
        // iOS 13+ 使用 WindowScene
        if #available(iOS 13.0, *) {
            rootViewController = UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .first?
                .windows
                .first(where: { $0.isKeyWindow })?
                .rootViewController
        }
        // iOS 12 及以下使用 keyWindow
        else {
            rootViewController = UIApplication.keyWindow?.rootViewController
        }
        
        return rootViewController?.findCurrentViewController()
    }
}

extension UIViewController {
    @MainActor
    func findCurrentViewController() -> UIViewController {
        if let nav = self as? UINavigationController {
            return nav.visibleViewController?.findCurrentViewController() ?? nav
        }
        if let tab = self as? UITabBarController {
            return tab.selectedViewController?.findCurrentViewController() ?? tab
        }
        if let presented = self.presentedViewController {
            return presented.findCurrentViewController()
        }
        return self
    }
}


