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

import UIKit
import CocoaLumberjack

let ddloglevel = DDLogLevel.verbose

@UIApplicationMain
class AppDelegate: UIResponder {
	// MARK: Public Properties
    var window: UIWindow?
	
	// MARK: Private Properties
	private(set) var spinnerManager: SpinnerManager? = nil
    private let preferences: Preferences
    private let playerController: PlayerControllerProtocol

	// MARK: Initializer
    override init() {
        preferences = Preferences()
        playerController = PlayerController(preferences: preferences)
        playerController.start()
        Logger.setup()
		
		HTTPServer.sharedInstance.localLibraryIdentifier = preferences.localMusicLibraryIdentifier()
    }
}

// MARK: - UIApplicationDelegate
extension AppDelegate: UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // The app's root view controller is a split view controller even though we may show an
        // interstitial T&Cs screen. This is the suggested design.
        Theming.themeUIComponents()

		HTTPServer.sharedInstance.start()
		UPnPManager.sharedInstance.start()
        
        let splitViewController = window!.rootViewController as! SplitViewController
        splitViewController.delegate = self
		splitViewController.preferredDisplayMode = .allVisible
        spinnerManager = SpinnerManager(rootViewController: splitViewController,
                                        playerController: playerController,
                                        preferences: preferences)
        
        for vc in splitViewController.viewControllers {
            vc.injectDependencies(preferences: preferences, playerController: playerController)
        }
        splitViewController.injectDependencies(preferences: preferences, playerController: playerController)
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

// MARK: - UISplitViewControllerDelegate
extension AppDelegate: UISplitViewControllerDelegate {
    func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
		// Is we're showing the empty detail don't show it when the split view collapses.
        return (secondaryViewController is NoSelectionNavigationController)
    }
	
	func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? {
		if needToShowNoSelection(primaryViewController: primaryViewController) {
			return NoSelectionNavigationController.instantiateFromStoryboard()
		}
		return .none // Do the default
	}
	
	func needToShowNoSelection(primaryViewController: UIViewController) -> Bool {
		guard let navController = primaryViewController as? UINavigationController,
			let detailViewNavController = navController.topViewController as? UINavigationController else {
			return true
		}
		return !(detailViewNavController is MiniPlayerHostingNavigationController)
	}
}


