//
//  NSObject+Extension.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2024/4/12.
//

import UIKit

// MARK: - NSObject 属性的扩展
public extension NSObject {
    
    // MARK: 类名（对象方法）
    /// 类名
    var className: String {
        return type(of: self).className
    }
    
    // MARK: 类名（类方法）
    /// 类名
    static var className: String {
        return String(describing: self)
    }
    
    func rootViewController() -> UIViewController? {
        guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first, let rootVC = window.rootViewController  else {
            return nil
        }
        return NSObject.top(rootVC: rootVC)
    }
    
    private static func top(rootVC: UIViewController?) -> UIViewController? {
        if let presentedVC = rootVC?.presentedViewController {
            return top(rootVC: presentedVC)
        }
        if let nav = rootVC as? UINavigationController,
            let lastVC = nav.viewControllers.last {
            return top(rootVC: lastVC)
        }
        if let tab = rootVC as? UITabBarController,
            let selectedVC = tab.selectedViewController {
            return top(rootVC: selectedVC)
        }
        return rootVC
    }
}

