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

import UIKit

class MediaServersViewController: MusicLibraryBaseViewController {
	private struct Segues {
		static let showItems = "showItems"
	}
	
	private var collectionViewHelper: MusicListDisplayHelper!
	private var mediaServersDelegate: MediaServersDataSourceDelegate?
	private var servers: [UPnPMediaServer] = []
	
	deinit {
		NotificationCenter.default.removeObserver(self)
	}
}

// MARK: - Overridden Methods
extension MediaServersViewController {
	override func viewDidLoad() {
        assert(playerGroup != nil)
		hasSearchButton = false
		super.viewDidLoad()
		
		title = NSLocalizedString("SERVERS", comment: "Media Server text")
		servers = UPnPManager.sharedInstance.mediaServers
		mediaServersDelegate = MediaServersDataSourceDelegate(servers: servers)
		let dataSource = MusicListDataSource(playerGroup: playerGroup!,
											 playerController: playerController,
											 delegate: mediaServersDelegate!)
		
		collectionViewHelper = MusicListDisplayHelper(dataSources: [dataSource],
													  viewController: self,
													  collectionView: collectionView!,
													  dragAllowed: false,
													  countUpdater: nil,
													  onItemSelected: { [weak self] indexPath, item in
														guard let self = self else {
															return
														}
														self.didSelect(row: indexPath.row, item: item)
														
			},
													  useNarrowRows: true)
		
		setupObservers()
	}
	
	override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
		if let itemVC = segue.destination as? MediaServerItemsViewController,
			let server = sender as? UPnPMediaServer {
			itemVC.injectDependencies(preferences: preferences, playerController: playerController)
			itemVC.playerGroup = playerGroup
			itemVC.mediaServer = server
			itemVC.title = server.name.uppercased()
		}
	}
}

// MARK: - Private Methods
extension MediaServersViewController {
	private func setupObservers() {
		NotificationCenter.default.addObserver(self,
											   selector: #selector(serversDidChange(_:)),
											   name: .uPnPMediaServersDidChange,
											   object: nil)
		
	}
	
	@objc private func serversDidChange(_ notification: Notification) {
		servers = UPnPManager.sharedInstance.mediaServers
		// Is there anything above us in stack?
		if let itemVC = navigationController?.topViewController as? MediaServerItemsViewController {
			if !servers.contains(itemVC.mediaServer!) {
				// The media server the drill down views were navigating has gone.
				navigationController?.popToViewController(self, animated: true)
			}
		}
		mediaServersDelegate?.forceReload(servers: servers)
	}

	private func didSelect(row: Int, item: MusicListDisplayHelperItem) {
		if let inputItem = item as? MediaServersMusicListDisplayHelperItem {
			performSegue(withIdentifier: Segues.showItems, sender: inputItem.server)
		}
	}
}

