//
// © 2017-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit
import CocoaLumberjack

protocol DetailNavigationController {
	func prepareForReplacement()
}

class DeviceDetailNavigationController: MiniPlayerHostingNavigationController, DetailNavigationController {
	private var PlayerGroupObserver: ObserverToken?

	deinit {
		if PlayerGroupObserver != nil {
			NotificationCenter.default.removeObserver(PlayerGroupObserver!)
			PlayerGroupObserver = nil
		}
	}
}

// MARK: - Overridden Methods
extension DeviceDetailNavigationController {
	override func viewDidLoad() {
		super.viewDidLoad()
		setUpPlayerGroupObserver()
	}
}

// MARK: - Public Methods
extension DeviceDetailNavigationController {
	func prepareForReplacement() {
		removeAnyModal()
	}
}

// MARK: - Private Methods
extension DeviceDetailNavigationController {
    private func setUpPlayerGroupObserver() {
        let PlayerGroupHandler: (PlayerGroupNotification) -> () = { [weak self] notification in
            guard let self = self,
                let group = self.playerGroup,
                notification.playerGroup == group  else {
                    return

            }

            if notification.reason == .removed {
                // We've been deleted!!!
                self.playerGroup = nil

                self.removeAnyModal()
                self.showOfflineOverlay()

                if let navController = self.splitViewController?.viewControllers.first as? UINavigationController {
                    navController.popToRootViewController(animated: true)
            	}
            }
		}
		
		PlayerGroupObserver = NotificationCenter.default.addObserver(forType: PlayerGroupNotification.self,
															  object: playerController,
															  queue: OperationQueue.main,
															  using: PlayerGroupHandler)
		
	}
    
    private func resetNavControllerStack() {
		removeAnyModal()
        popToRootViewController(animated: false)
    }
	
	private func removeAnyModal() {
		if let _ = presentedViewController {
			dismiss(animated: false, completion: nil)
		} else {
			for vc in viewControllers {
				if vc.presentedViewController != nil {
					vc.dismiss(animated: false, completion: nil)
				}
			}
		}
	}
	
	private func showOfflineOverlay() {
		let overlay = NoSelectionViewController.instantiateFromStoryboard()
		viewControllers = [overlay]
	}
}
