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

import UIKit
import CocoaLumberjack

class InputSourcesViewController: MusicLibraryBaseViewController {
	private var collectionViewHelper: MusicListDisplayHelper!
	private var inputSourcesDelegate: InputSourcesDataSourceDelegate?
	private var observers = [ObserverToken] ()
	
	deinit {
		observers.forEach { NotificationCenter.default.removeObserver($0) }
		observers.removeAll()
	}
}

// MARK: - Overridden Methods
extension InputSourcesViewController {
	override func viewDidLoad() {
        assert(playerGroup != nil)
		hasSearchButton = false
		super.viewDidLoad()
		
		title = NSLocalizedString("AUDIO SOURCES", comment: "Audio Sources text")
		
        inputSourcesDelegate = InputSourcesDataSourceDelegate(playerGroup: playerGroup!, playerController: playerController)
		let dataSource = MusicListDataSource(playerGroup: playerGroup!,
											 playerController: playerController,
											 delegate: inputSourcesDelegate!)
		
		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()
	}
}

// MARK: - Private Methods
extension InputSourcesViewController {
	private func setupObservers() {
		let playerHandler: (PlayerNotification) -> () = { [weak self] notification in
			guard let self = self else { return }
			
			if notification.reason == .inputSelectorChanged {
				self.inputSourcesDelegate?.forceReload()
			}
		}
		
		let playerObserver = NotificationCenter.default.addObserver(forType: PlayerNotification.self,
																	object: playerController,
																	queue: OperationQueue.main,
																	using: playerHandler)
		
		observers.append(playerObserver)
	}

	private func didSelect(row: Int, item: MusicListDisplayHelperItem) {
		guard let inputItem = item as? InputSourcesOutputSinksMusicListDisplayHelperItem else {
			return
		}
		
		let player = inputItem.player
		let selector = inputItem.source
		DDLogVerbose("Attempting to set input selector: \(selector) on player: \(player.displayName)")
        player.setInputSelector(selector,
                                completion: { (success, e) in
                                    if !success, let error = e {
										DDLogError("Error setting input selector: \(error)")
                                    }
        }, completionQueue: DispatchQueue.main)
	}
}
