//
//  UIViewControllerExtensions.swift
//  GoogleUtilities
//
//  Created by cxb on 2023/5/23.
//

import UIKit
extension UIApplication {
    
    var window: UIWindow? {
        if #available(iOS 13.0, *) {
            let windows: [UIWindow] = UIApplication.shared.connectedScenes.compactMap { scene in
                guard let scene = scene as? UIWindowScene else { return nil }
                guard scene.session.role == .windowApplication else { return nil }
                guard let delegate = scene.delegate as? UIWindowSceneDelegate else { return nil }
                guard let window = delegate.window else { return nil }
                guard let window = window else { return nil }
                return window
            }
            
            if windows.isEmpty {
                guard let delegate = UIApplication.shared.delegate else { return nil }
                guard let window = delegate.window else { return nil }
                return window
                
            } else {
                return windows.first
            }
            
        } else {
            guard let delegate = UIApplication.shared.delegate else { return nil }
            guard let window = delegate.window else { return nil }
            return window
        }
    }
}
extension UIViewController {
    
    /// 获取Window下的顶层控制器
    open class func top(in window: UIWindow? = .none) -> UIViewController? {
        return (window ?? UIApplication.shared.window)?.rootViewController?.top()
    }
    
    open func top() -> UIViewController {
        // presented view controller
        if let controller = presentedViewController {
            return controller.top()
        }
        
        // UITabBarController
        if let tabBarController = self as? UITabBarController,
           let controller = tabBarController.selectedViewController {
            return controller.top()
        }
        
        // UINavigationController
        if let navigationController = self as? UINavigationController,
           let controller = navigationController.visibleViewController {
            return controller.top()
        }
        
        // UIPageController
        if let pageViewController = self as? UIPageViewController,
           pageViewController.viewControllers?.count == 1 ,
           let controller = pageViewController.viewControllers?.first {
            return controller.top()
        }
        
        // child view controller
        //        for subview in self.view?.subviews ?? [] {
        //            if let controller = subview.next as? UIViewController {
        //                return controller.top()
        //            }
        //        }
        return self
    }
}
