//
//  WindowHelper.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import UIKit

class WindowHelper {
    
    /// 获取当前的 keyWindow
    static func getKeyWindow() -> UIWindow? {
        // 在 iOS 13 及以上，SceneDelegate 管理窗口
        if #available(iOS 13.0, *) {
            return UIApplication.shared.connectedScenes
                .compactMap { $0 as? UIWindowScene }
                .flatMap { $0.windows }
                .first { $0.isKeyWindow }
        } else {
            // iOS 13 以下直接获取 keyWindow
            return UIApplication.shared.keyWindow
        }
    }
    
    /// 获取当前窗口，兼容 iOS 13 及以上版本
    static func getCurrentWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            // iOS 13 及以上使用 `scene` 获取当前 window
            guard let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
                return nil
            }
            return scene.windows.first { $0.isKeyWindow }
        } else {
            // iOS 12 及以下直接从 keyWindow 获取
            return UIApplication.shared.keyWindow
        }
    }
    
    /// 获取当前根视图控制器
    static func getRootViewController() -> UIViewController? {
        guard let window = getCurrentWindow() else {
            return nil
        }
        return window.rootViewController
    }
    
    /// 获取当前的视图控制器
    static func getCurrentViewController() -> UIViewController? {
        var currentViewController = getRootViewController()
        
        while let presentedViewController = currentViewController?.presentedViewController {
            currentViewController = presentedViewController
        }
        
        return currentViewController
    }
    
    
    static func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        } else if let tab = base as? UITabBarController {
            return topViewController(base: tab.selectedViewController)
        } else if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        debugPrint("当前顶层 VC 是: \(base)")
        return base
    }
}
