//
//  UIViewController+GDNavigation.swift
//  GDKit
//
//  Created by SJ on 2022/1/15.
//

import UIKit

// MARK: - 获取当前控制器
extension UIViewController {
    
    //    获取当前正呈现的UIViewController
    static var current:UIViewController? {
        let delegate  = UIApplication.shared.delegate as? AppDelegate
        var current = delegate?.window?.rootViewController
        
        while (current?.presentedViewController != nil)  {
            current = current?.presentedViewController
        }
        
        if let tabbar = current as? UITabBarController , tabbar.selectedViewController != nil {
            current = tabbar.selectedViewController
        }
        
        while let navi = current as? UINavigationController , navi.topViewController != nil  {
            current = navi.topViewController
        }
        return current
    }
    
    //获取UINavigationController的topViewController
    static var navTopViewController: UIViewController? {
        let delegate  = UIApplication.shared.delegate as? AppDelegate
        var current = delegate?.window?.rootViewController
        
        if let tabbar = current as? UITabBarController , tabbar.selectedViewController != nil {
            current = tabbar.selectedViewController
        }
        
        while let navi = current as? UINavigationController , navi.topViewController != nil  {
            current = navi.topViewController
        }
        return current
    }
    
    class func classFromString(_ className:String) -> UIViewController? {
        //1、获swift中的命名空间名
        var name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String
        //2、如果包名中有'-'横线这样的字符，在拿到包名后，还需要把包名的'-'转换成'_'下横线
        name = name?.replacingOccurrences(of: "-", with: "_")
        //3、拼接命名空间和类名，”包名.类名“
        let fullClassName = name! + "." + className
        //通过NSClassFromString获取到最终的类，由于NSClassFromString返回的是AnyClass，这里要转换成UIViewController.Type类型
        guard let classType = NSClassFromString(fullClassName) as? UIViewController.Type else {
            //fatalError("转换失败")
            return nil
        }
        return classType.init()
    }
    
    
}
