//
//  MIScreenManager.swift


import Foundation
import UIKit
import StoreKit

let ScreenManagerShared = ScreenManager.shared

class ScreenManager: NSObject {
    
    //MARK: - Variable
    static let shared = ScreenManager()
    var presentedModalController: BaseViewController?
    
    // MARK: - Functions to load specific screens
    func moveToHomeVC(){
        Utilities.openHome()
    }
    
    func moveToLoginVC(){
        let loginVC = AppStoryBoard.LWLanding().instantiateViewController(withIdentifier: LWLoginVC.identifier) as! LWLoginVC
        loginVC.viewControllerPresentationStyle = .push
        loginVC.showNavigationBar               = false
        self.loadScreen(loginVC, animated: true)
    }
    func moveToCountryPickerVC(countryData : [CountryListModel] ,clouser:@escaping(_ objCountry: CountryListModel?) -> ()){
        let countryVC = AppStoryBoard.LWLanding().instantiateViewController(withIdentifier: LWCountryPickerVC.identifier) as! LWCountryPickerVC
        countryVC.arrCountry = countryData
        countryVC.arrSearchCountry = countryData
        countryVC.viewControllerPresentationStyle = .modal
        countryVC.showNavigationBar               = false
        countryVC.modalPresentationStyle          = DeviceType.ISPAD ? .pageSheet : .formSheet
        countryVC.completionPickedCountry = { [weak self] (countryData) in
            if let _ = self {
                clouser(countryData)
            }
        }
        self.loadScreen(countryVC, animated: true)
    }
    func moveToVrifyOTPVC(mobilenumber:String = ""){
        let otpVC = AppStoryBoard.LWLanding().instantiateViewController(withIdentifier: LWVerifyOTPVC.identifier) as! LWVerifyOTPVC
        otpVC.viewControllerPresentationStyle = .push
        otpVC.showNavigationBar               = false
        otpVC.mobileNumber                    = mobilenumber
        otpVC.modalPresentationStyle          = .fullScreen
        self.loadScreen(otpVC, animated: true)
    }
    func moveToUserNameVC(){
        let userVC = AppStoryBoard.LWLanding().instantiateViewController(withIdentifier: LWUserNameSetupVC.identifier) as! LWUserNameSetupVC
        userVC.viewControllerPresentationStyle = .push
        userVC.showNavigationBar               = false
        userVC.modalPresentationStyle          = .fullScreen
        self.loadScreen(userVC, animated: true)
    }
    
    func moveToAddFriendVC(selectedTab : Int){
        let addFriendVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: AddFriendViewController.identifier) as! AddFriendViewController
        addFriendVC.selectedTab = selectedTab
        addFriendVC.viewControllerPresentationStyle = .push
        addFriendVC.showNavigationBar               = false
        addFriendVC.modalPresentationStyle          = .fullScreen
        self.loadScreen(addFriendVC, animated: true)
    }
    
    func moveToPickFriendVC(capturedImage : UIImage?,isFromHistory: Bool, imageId : Int?,clouser:@escaping(_ isPhotoSent: Bool?) -> ()){
        let pickFriendVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: PickFriendViewController.identifier) as! PickFriendViewController
        pickFriendVC.isFromHistoryVC = isFromHistory
        pickFriendVC.capturedImage = capturedImage ?? UIImage()
        pickFriendVC.imageId = imageId ?? 0
        pickFriendVC.viewControllerPresentationStyle = .modal
        pickFriendVC.modalPresentationStyle          = DeviceType.ISPAD ? .fullScreen : .formSheet //
        pickFriendVC.isPhotoSent = { [weak self] (success) in
            if let _ = self {
                clouser(success)
            }
        }
        self.loadScreen(pickFriendVC, animated: true)
    }
    
    func presentToContactVC(arrFriendList : [FriendListModel], arrPendingList : [PendingFriendReqListModel], arrFriendReqList : [ReceivedReqListModel]){
        let contactVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: ContactListViewController.identifier) as! ContactListViewController
        contactVC.arrFriendList = arrFriendList
        contactVC.arrPendingList = arrPendingList
        contactVC.arrFriendReqList = arrFriendReqList
        contactVC.isFromLoginScreen = false
        contactVC.viewControllerPresentationStyle = .modal
//        contactVC.modalPresentationStyle          = .formSheet
        contactVC.modalPresentationStyle          = DeviceType.ISPAD ? .currentContext : .formSheet
        self.loadScreen(contactVC, animated: true)
    }
    func showHistoryVC(){
        let historyVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: HistoryViewController.identifier) as! HistoryViewController
        historyVC.modalPresentationStyle = DeviceType.ISPAD ? .fullScreen : .formSheet
        self.loadScreen(historyVC, animated: true)
    }
    
    func moveToContactVC(){

        let contactVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: ContactListViewController.identifier) as! ContactListViewController
        contactVC.showNavigationBar = false
        contactVC.isFromLoginScreen = true
        contactVC.viewControllerPresentationStyle = .push
        contactVC.modalPresentationStyle          = .fullScreen
        self.loadScreen(contactVC, animated: true)
    }
    
    func presentToHelpScreen(){
        let helpVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: HelpViewController.identifier) as! HelpViewController
        helpVC.viewControllerPresentationStyle = .modal
        helpVC.modalPresentationStyle = DeviceType.ISPAD ? .pageSheet : .formSheet
        helpVC.isFromLoginView = false
        self.loadScreen(helpVC, animated: true)
    }
    
    func moveToHelpScreen(){
        let helpVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: HelpViewController.identifier) as! HelpViewController
        helpVC.showNavigationBar = false
        helpVC.viewControllerPresentationStyle = .push
        helpVC.modalPresentationStyle = .fullScreen
        helpVC.isFromLoginView = true
        self.loadScreen(helpVC, animated: true)
    }
    
    func moveToSettingVC(){
        let addFriendVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: SettingViewController.identifier) as! SettingViewController
        addFriendVC.viewControllerPresentationStyle = .push
        addFriendVC.showNavigationBar               = false
        addFriendVC.modalPresentationStyle          = .fullScreen
        self.loadScreen(addFriendVC, animated: true)
    }
    
    func moveToCustomRating(){
        let ratingVC = AppStoryBoard.LWHome().instantiateViewController(withIdentifier: CustomRatingViewController.identifier) as! CustomRatingViewController
        ratingVC.modalPresentationStyle = .overFullScreen
        self.loadScreen(ratingVC, animated: true)
    }
    
    func showNativeReviewPopup(){
        DispatchQueue.main.async {
            if let scene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
                SKStoreReviewController.requestReview(in: scene)
            }
        }
    }
    
    // MARK: - Common functions
    func loadScreen(_ controller: BaseViewController, animated: Bool) {
        
        DispatchQueue.main.async {
            switch controller.viewControllerPresentationStyle {
            case .push:
                if controller.showNavigationBar {
                    controller.addBarButton(type: .back, position: .left)
                }
                self.pushViewController(controller: controller, isAnimated: animated)
                
            case .modal, .transparentModal:
                self.presentViewController(controller: controller, isAnimated: animated)
                
            case .root:
                let navigation = UINavigationController(rootViewController: controller)
                APPDEL.window?.rootViewController = navigation
            }
        }
    }
    
    func pushViewController(controller: BaseViewController, isAnimated animated: Bool) {
        
        
        let topViewController = self.getTopViewController()
        controller.viewControllerPresentationStyle = PresentationStyle.push
        topViewController?.navigationController?.pushViewController(controller, animated: animated)
        
        return;
      
        controller.viewControllerPresentationStyle = .push
        var isAnimate = animated
        if controller.viewControllerTransitionSubtype != .fromRight {
            
            isAnimate           = false
            let transition      = CATransition()
            transition.duration = 0.5
            transition.type     = CATransitionType.push
            transition.subtype  = CATransitionSubtype(rawValue: controller.transitionSubtypeFromViewController(transitionSubType: controller.viewControllerTransitionSubtype))
            APPDEL.window!.layer.add(transition, forKey: kCATransition)
        }
        
        let decoratedController: UIViewController = controller
        
        if let rootViewController: UINavigationController = APPDEL.window?.rootViewController as? UINavigationController {
            controller.viewControllerPresentationStyle = PresentationStyle.push
            rootViewController.pushViewController(decoratedController, animated: isAnimate)
        } else {
            APPDEL.window?.rootViewController = UINavigationController(rootViewController: decoratedController)
        }
        
    }
    
    func presentViewControllerWithoutNavigation(controller: BaseViewController, isAnimated animated: Bool) {
        
        DispatchQueue.main.async {
            controller.viewControllerPresentationStyle = PresentationStyle.modal
            controller.present(controller, animated: animated, completion: nil)
        }
    }
    
    func closePresentedModal() {
        presentedModalController?.goBack(animated: true)
    }
    
    func presentViewController(controller: BaseViewController, isAnimated animated: Bool) {
        
        let topViewController = self.getTopViewController()
        
        if controller.viewControllerPresentationStyle == .transparentModal {
            controller.modalPresentationStyle  = UIModalPresentationStyle.overCurrentContext
            controller.isTransparentBackground = true
        } else {
            controller.viewControllerPresentationStyle = PresentationStyle.modal
        }
        presentedModalController = controller
        
        DispatchQueue.main.async {
            if controller.showNavigationBar {
                let navigationController = UINavigationController(rootViewController: controller)
                topViewController?.present(navigationController, animated: animated, completion: nil)
            } else {
                topViewController?.present(controller, animated: animated, completion: nil)
            }
        }
        
    }
    
    func getTopViewController() -> UIViewController? {
        
        guard let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return nil
        }
        let controller = (appDelegate.window?.rootViewController)!
        var activeController: UIViewController!
        
        if controller.isKind(of: UITabBarController.self) {
            if let tabBarController: UITabBarController = controller as? UITabBarController {
                let nextViewController = tabBarController.selectedViewController!
                
                if nextViewController.isKind(of: UINavigationController.self) {
                    if let navController = nextViewController as? UINavigationController {
                        activeController = self.getTopMostController(navController: navController)
                    }
                } else {
                    activeController = nextViewController
                }
            }
        } else if controller.isKind(of: UINavigationController.self) {
            if let navController = controller as? UINavigationController {
                activeController = self.getTopMostController(navController: navController)
            }
        } else {
            if let presentedController = controller.presentedViewController {
                activeController = presentedController
            } else {
                activeController = controller
            }
        }
        
        return activeController
    }
    
    func getTopMostController(navController: UINavigationController) -> UIViewController {
        var controller: UIViewController!
        
        if let presentedController = navController.topViewController?.presentedViewController {
            controller = presentedController
        } else {
            controller = navController.topViewController
        }
        
        return controller
    }
}
