//
//  CBBaseViewController.swift

import UIKit
import SafariServices

enum PresentationStyle {
    case modal
    case transparentModal
    case push
    case root
}

enum TransitionSubtype {
    case fromLeft
    case fromRight
    case fromTop
    case fromBottum
}

enum StatusBarStyle: Int {
    case light
    case dark
}

class BaseViewController: UIViewController {
    
    //MARK:- Variables
    
    var viewControllerPresentationStyle: PresentationStyle  = .modal
    var viewControllerTransitionSubtype: TransitionSubtype  = .fromRight
    var showNavigationBar: Bool                             = false
    var navigationTitle: String                             = ""
    var showLoadingIndicator: Bool                          = false
    var statusBarStyle: StatusBarStyle                      = .dark
    var transparencyBackground: UIColor                     = UIColor.black
    var isTransparentBackground: Bool                       = false
    var isNavigationBarSeperator: Bool                      = false
    var showSideMenu: Bool                                  = false
    var showTitleIcon: Bool                                 = false

    //MARK:- Overrided functions from base class
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
//        for family in UIFont.familyNames.sorted() {
//            let names = UIFont.fontNames(forFamilyName: family)
//            debugPrint("Family: \(family) Font names: \(names)")
//        }
        hideKeyboardWhenTappedAround()
        initialObjects()
    }
    
    func initialObjects() {
        self.navigationController?.isNavigationBarHidden = !self.showNavigationBar
        if self.showNavigationBar {
            self.configureNavigationBar()
        }
        if self.isTransparentBackground {
            self.view.backgroundColor = self.transparencyBackground
        }
        
//        self.navigationController?.delegate = self
    }
        
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
       
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        
        super.viewDidDisappear(animated)
        
        if self.viewControllerPresentationStyle == .modal || viewControllerPresentationStyle == .transparentModal {
                ScreenManager.shared.presentedModalController = nil
        }
    }
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    override func didReceiveMemoryWarning() {
        
        super.didReceiveMemoryWarning()
    }
    
    // MARK: - Navigation Bar methods
    
    func configureNavigationBar() {
        //setStatusBar()

        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage   = UIImage()
        self.navigationController?.navigationBar.isTranslucent = false
//        self.navigationController?.navigationBar.barTintColor  = MIColor.AppBtnClr
//        let titleFont = Font.HelveticaNeue_Bold(fontSize: 18)//CBFont.Semibold(fontSize: 20)
//        self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: titleFont ]
    
        if showTitleIcon {
            self.setNavigationBarTitleIcon()
        } else {
            self.setNavigationBarTitle(ttl: self.navigationTitle)
        }
    }
    
    func setNavigationBarTitle(ttl: String) {
        //self.title = ttl
        self.navigationItem.title = ttl
    }
    
    func setNavigationBarTitleIcon() {
        let logo = UIImage(named: "nav_icon")
        let navView = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 50))
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 150, height: 40))
        imageView.image = logo
        imageView.contentMode = .scaleAspectFit
        navView.addSubview(imageView)

        self.navigationItem.titleView = navView
    }
    
    func setStatusBar() {
        if #available(iOS 13.0, *) {
            let statusBar = UIView(frame: UIApplication.shared.keyWindow?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero)
             statusBar.backgroundColor = UIColor.white
             UIApplication.shared.keyWindow?.addSubview(statusBar)
        } else {
             UIApplication.shared.statusBarView?.backgroundColor = UIColor.init(red: 243/250, green: 243/250, blue: 243/250, alpha: 1)
        }
    }
    
    func addBarButton(type: CustomBarButtonType, position: CustomBarButtonPosition) {
        
        let barButton: CustomBarButton!
        if let barButtonTitle = CustomBarButton.titleForButtonType(type) {
            // Bar Button with Title
            barButton = CustomBarButton(title: barButtonTitle, style: .plain, target: self, action: #selector(navigationBarButtonTapped(sender:)))
            barButton.tintColor = UIColor.white
            //if let font = CBFont.Regular(fontSize: 14.0) {
            //}
//            barButton.setTitleTextAttributes([ NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white ], for: .normal)
//            barButton.setTitleTextAttributes([ NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white ], for: .selected)
        } else {
            
            if let title = getLeftButtonTitle() {
                
                barButton = CustomBarButton(title: title, style: .plain, target: self, action: #selector(navigationBarButtonTapped(sender:)))
                
                //if let font = CBFont.Regular(fontSize: 14.0) {
                    
//                barButton.setTitleTextAttributes([ NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white ], for: .normal)
//                barButton.setTitleTextAttributes([ NSAttributedString.Key.font: Font.HelveticaNeue_Medium(fontSize: 14), NSAttributedString.Key.foregroundColor: UIColor.white ], for: .selected)
                //}
                
            } else {
                
                let barButtonImage = CustomBarButton.imageForButtonType(type)
                barButton = CustomBarButton(image: barButtonImage, style: .plain, target: self, action: #selector(navigationBarButtonTapped(sender:)))
            }
        }
        barButton.buttonType = type
        
        position == .left ? self.addBarButtonToLeft(button: barButton) : self.addBarButtonToRight(button: barButton)
    }
    
    func getLeftButtonTitle() -> String? {
        
        return nil
    }
    
    private func addBarButtonToLeft(button: CustomBarButton) {

        var items: [UIBarButtonItem] = []

        if let barItems = self.navigationItem.leftBarButtonItems {

            items = barItems
        }
        
        items.append(button)
        
        self.navigationItem.leftBarButtonItems = items
    }
    
    private func addBarButtonToRight(button: CustomBarButton) {
        
        var items: [UIBarButtonItem] = []
        
        if let barItems = self.navigationItem.rightBarButtonItems {
            
            items = barItems
        }
        
        items.append(button)
        self.navigationItem.rightBarButtonItems = items
    }
    
    func addNavigationBarTitleView(viewSize: CGRect, imageName: String) {
        
        let titleView      = UIView(frame: viewSize)
        let titleImageView = UIImageView(image: UIImage(named: imageName))
        titleImageView.frame = CGRect(x: 0.0, y: 0.0, width: titleView.frame.width, height: titleView.frame.height)
        titleImageView.contentMode = .center
        titleView.addSubview(titleImageView)
        navigationItem.titleView = titleView
    }
    
    @objc func navigationBarButtonTapped(sender: CustomBarButton) {
        
        self.view.endEditing(true)
        
        switch sender.buttonType {

        case .back:
            self.goBack(animated: true)

        case .sync:
            self.syncButtonPressed()
            
        case .add:
            self.addButtonPressed()
            
        case .setting:
            self.settingButtonPressed()
            
        default:
            break
        }
    }
    
    // MARK: - Custom Bar Button Methods
    
    func customNavigationOptionsAction(sender: AnyObject) {
        
        //Implementation in its sub class.
        //CBCommon.showSimpleAlert(message: "generic.notImplementedlocalized", controller: self)
    }
    
    func imageForCustomNavigationBarButton() -> UIImage? {
        
        return #imageLiteral(resourceName: "moreOptions")
    }
    
    // MARK: - screen navigation
    
    func goBack(animated: Bool) {
        
        switch self.viewControllerPresentationStyle {
            
        case .push:
            dismissDetail(animated: animated)
        case .modal, .transparentModal:
            self.dismiss(animated: true, completion: nil)
        case .root:
            moveBackFromRootController()
        }
    }
    
    func revealToggle(sender: AnyObject) {
        
    }

    func dismissDetail(animated: Bool) {
        
        if self.viewControllerTransitionSubtype == .fromRight {
            
            self.navigationController?.popViewController(animated: animated)
        } else {
            
            let transition      = CATransition()
            transition.duration = 0.50
            transition.type     = CATransitionType.push
            transition.subtype  = CATransitionSubtype(rawValue: transitionSubtypeForDismissFromViewController(transitionSubType: self.viewControllerTransitionSubtype))
            
            self.view.window!.layer.add(transition, forKey: kCATransition)
            self.navigationController?.popViewController(animated: false)
        }
    }
    
    func moveBackFromRootController() {
        
    }
    
    // MARK: - Screen Rotation
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.canAutorotate() ? .allButUpsideDown : .portrait
    }
    
    override var shouldAutorotate: Bool {
        return true
    }
    
    func canAutorotate() -> Bool {
        return false
    }
    
    @objc func deviceOrientationChanged() {
        if self.showNavigationBar == true {
            let isNavigationBarHidden = UIApplication.shared.statusBarOrientation.isLandscape ? true : false
            self.navigationController?.setNavigationBarHidden(isNavigationBarHidden, animated: true)
        }
    }
    
    // MARK: - Transition Subtype in Push

    func transitionSubtypeFromViewController(transitionSubType: TransitionSubtype) -> String {
        
        var subtype = ""
        
        switch transitionSubType {
        case .fromLeft:
            subtype = CATransitionSubtype.fromLeft.rawValue
        case .fromTop:
            subtype = CATransitionSubtype.fromBottom.rawValue
        case .fromBottum:
            subtype = CATransitionSubtype.fromTop.rawValue
        default://.fromRight
            subtype = CATransitionSubtype.fromRight.rawValue
        }
        
        return subtype
    }

    func transitionSubtypeForDismissFromViewController(transitionSubType: TransitionSubtype) -> String {
        
        var subtype = ""
        
        switch transitionSubType {
        case .fromLeft:
            subtype = CATransitionSubtype.fromRight.rawValue
        case .fromTop:
            subtype = CATransitionSubtype.fromTop.rawValue
        case .fromBottum:
            subtype = CATransitionSubtype.fromBottom.rawValue
        default://.fromRight
            subtype = CATransitionSubtype.fromLeft.rawValue
        }
        
        return subtype
        
    }

    
    //MARK- Button Action
    func editButtonPressed() {
        // Implementation in subclass
    
    }
    func skipButtonPressed() {
        // Implementation in subclass
    }
    
    func cancelButtonPressed() {
        // Implementation in subclass
    }
    
    func syncButtonPressed() {
        // Implementation in subclass
    }
    
    func addButtonPressed() {
        // Implementation in subclass
    }
    
    func refreshButtonPressed() {
        // Implementation in subclass
    }
    
    func alternateButtonPressed() {
        // Implementation in subclass
    }
    
    func recordButtonPressed() {
        // Implementation in subclass
    }
    func settingButtonPressed() {
        // Implementation in subclass
    }
    
    func getTopView() -> UIView {
        return UIApplication.shared.keyWindow!
    }
    
    // MARK: - Activity Indicator
    func showActivityIndicator(message: String? = nil) {
        
    }
    
    func hideActivityIndicator() {
        
    }
    
    func updateActivityIndicator(message: String?) {
        
    }
    
    // MARK: - WebView
    func presentWebView(url: String) {
        if let safariUrl = URL(string: url) {
            let safariViewController = SFSafariViewController(url: safariUrl)
            self.present(safariViewController, animated: true, completion: nil)
        }
    }
 }

extension UIViewController {
    @objc public func navigationControllerSupportedInterfaceOrientations(_ navigationController: UINavigationController) -> UIInterfaceOrientationMask {
        debugPrint("")
        return (navigationController.topViewController?.supportedInterfaceOrientations)!
    }
}

extension UIApplication {
    var statusBarView: UIView? {
        if responds(to: Selector(("statusBar"))) {
            return value(forKey: "statusBar") as? UIView
        }
        return nil
    }
 
    func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
    
    class func getTopViewController(base: UIViewController? = APPDEL.window?.rootViewController) -> UIViewController? {

        var baseVC : UIViewController!
        
        if base == nil {
            baseVC = UIApplication.shared.windows.filter {$0.isKeyWindow}.first?.rootViewController
            //UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        }
        else {
            baseVC = base
        }
        
        if let nav = baseVC as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)

        } else if let tab = baseVC as? UITabBarController, let selected = tab.selectedViewController {
            return getTopViewController(base: selected)

        } else if let presented = baseVC?.presentedViewController {
            return getTopViewController(base: presented)
        }
        return base
    }
}
