//
//  UIApplication+extension.swift
//  Moon
//
//  Created by Robin on 2022/9/4.
//

import UIKit

public typealias App = UIApplication

public extension UIApplication {
    
    class var currentWindow: UIWindow? {
        if #available(iOS 13, *) {
            guard let curWinScene = shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else {
                return nil
            }
            if #available(iOS 15.0, *) {
                return curWinScene.keyWindow
            } else {
                return curWinScene.windows.first(where: {$0.isKeyWindow})
            }
        } else {
            return shared.keyWindow
        }
    }
    
    class var topPresentPage: UIViewController? {
        guard var posVC = currentWindow?.rootViewController else { return nil }
        while let presentedVC = posVC.presentedViewController {
            posVC = presentedVC
        }
        return posVC
    }
    
    class var currentPage: UIViewController? {
        guard var posVC = topPresentPage else { return nil }
        
        while posVC.isKind(of: UITabBarController.self) || posVC.isKind(of: UINavigationController.self) {
            if let tabbarPage = posVC as? UITabBarController {
                guard let selectedPage = tabbarPage.selectedViewController else { break }
                posVC = selectedPage
            }
            if let navPage = posVC as? UINavigationController {
                guard let topPage = navPage.topViewController else { break }
                posVC = topPage
            }
        }
        
        return posVC
    }
    
    class func present(_ viewController: UIViewController) {
        guard let topPresentPage = topPresentPage else { return }
        topPresentPage.present(viewController, animated: true)
    }
    
}
