//  UNPresentationService.swift

import Foundation
import UIKit

protocol UNPresentationServicing {
    func requestTopController() -> UIViewController?
}

class UNPresentationService: UNPresentationServicing {
    func requestTopController() -> UIViewController? {
        guard let appWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }),
              let topController = self.topViewController(fromBase: appWindow.rootViewController)
        else {
            print("Error - while tring to find the top View Controller")
            return nil
        }
        return topController
    }
}


fileprivate extension UNPresentationService {
    func topViewController(fromBase base: UIViewController?) -> UIViewController? {
        // Finding top view controller from base. Using recursion in this function
        if let navController = base as? UINavigationController {
            return topViewController(fromBase: navController.visibleViewController)
        } else if let tabController = base as? UITabBarController {
            if let selectedTab = tabController.selectedViewController {
                return topViewController(fromBase: selectedTab)
            }
        } else if let presentedController = base?.presentedViewController {
            return topViewController(fromBase: presentedController)
        }
        return base
    }
}
