import UIKit

class MainSplitController: UISplitViewController, UISplitViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.preferredDisplayMode = .allVisible
        self.delegate = self
    }
    
    func splitViewController(_ splitViewController: UISplitViewController, showDetail vc: UIViewController, sender: Any?) -> Bool {
        if self.isCollapsed {
            let tabController = self.viewControllers.first as? UITabBarController
            let selectedNavController = tabController?.selectedViewController
            
            var vcToPush = vc
            if let nav = vc as? UINavigationController {
                vcToPush = nav.topViewController!
            }
            
            vcToPush.hidesBottomBarWhenPushed = true
            selectedNavController?.show(vcToPush, sender: self)
            return true
        }
        
        return false
    }
    
    func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController?
    {
        let tabController = splitViewController.viewControllers.first as? UITabBarController
        let selectedNavController = tabController?.selectedViewController as? UINavigationController
        
        if selectedNavController?.viewControllers.count ?? 0 > 1 && selectedNavController?.viewControllers[1] is ReportController {
            if let controllers = selectedNavController?.popToRootViewController(animated: false) {
                let nav  = UINavigationController()
                nav.setViewControllers(controllers, animated: true)
                return nav
            }
        }
        
        return nil
    }
    
    func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool
    {
        guard let detailNav = secondaryViewController as? UINavigationController,
            let detail = detailNav.viewControllers.first as? ReportController
            else
        {
            return false
        }
        
        if detail.number == nil {
            return false
        }
        
        if let tabController = primaryViewController as? UITabBarController {
            let selectedNavController = tabController.selectedViewController as? UINavigationController
            detail.hidesBottomBarWhenPushed = true
            selectedNavController?.setNavigationBarHidden(false, animated: false)
            selectedNavController?.pushViewController(detail, animated: false)
            return true
        }
        
        return false
    }
}
