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

import UIKit

class SettingsNavigationController: UINavigationController, DetailNavigationController {

    private var deviceObserver: ObserverToken?
    var deviceID: String?

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

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

    override func viewWillAppear(_ animated: Bool) {
        if deviceID == nil {
            showUnavailableOverlay()
        }
    }
}

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

// MARK: - Private Methods
extension SettingsNavigationController {
    private func setUpDeviceObserver() {
        let deviceHandler: (DeviceNotification) -> () = { [weak self] notification in
            guard
                let self = self,
                notification.device.deviceID == self.deviceID else {
                    return
            }

            if notification.reason == .removed {
                // We've been deleted!!!
                self.deviceID = nil
                self.removeAnyModal()
                if let navController = self.splitViewController?.viewControllers.first as? UINavigationController {
                    navController.popToRootViewController(animated: true)
                }
            }
        }

        deviceObserver = NotificationCenter.default.addObserver(forType: DeviceNotification.self,
                                                                     object: playerController,
                                                                     queue: OperationQueue.main,
                                                                     using: deviceHandler)

    }

    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 showUnavailableOverlay() {
        let overlay = SettingsUnavailableViewController.instantiateFromStoryboard()
        viewControllers = [overlay]
    }
}
