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

import UIKit
import CocoaLumberjack

class PlaylistSongsViewController: MusicLibraryBaseViewController {
	var playlist: UserPlaylist?
	
	// MARK: Private Properties/Types
	private struct Segues {
		static let dismiss = "dismiss"
		static let choosePlaylist = "choosePlaylist"
	}
	
	private var collectionViewHelper: MusicListDisplayHelper!
	private var playlistDelegate: PlaylistSongsDataSourceDelegate?
	private var playlistDataSource: MusicListDataSource?
	private var addToPlaylistCompletion: MusicListDataSource.OnAddToPlaylistCompletion?
	
	// MARK: UI Outlets
	@IBOutlet private weak var emptyView: UIView?
}

// MARK:- Overridden Methods
extension PlaylistSongsViewController {
	override func viewDidLoad() {
        assert (playerGroup != nil)
		super.viewDidLoad()
		
		self.delegate = self
		setUpHelpers()
		title = playlist?.name.uppercased()
		emptyView?.alpha = playlistDataSource!.numberOfItems() == 0 ? 1.0 : 0.0
	}
}

// MARK:- UI Actions
extension PlaylistSongsViewController {
	@IBAction private func returnFromPlaylistChooser(segue: UIStoryboardSegue) {
		guard let chooserVC = segue.source as? PlaylistChooserTableViewController,
			let completion = addToPlaylistCompletion else {
				return
		}
		
		DDLogVerbose("Add to playlist: \(String (describing: chooserVC.chosenPlaylist?.name))")
		completion(chooserVC.chosenPlaylist)
	}
}

// MARK:- Private Methods
extension PlaylistSongsViewController {
	private func setUpHelpers() {
		playlistDelegate = PlaylistSongsDataSourceDelegate(playlist: playlist!)
		playlistDataSource = MusicListDataSource(playerGroup: playerGroup!,
												 playerController: playerController,
												 delegate: playlistDelegate!)
		playlistDataSource?.userPlaylistDelegate = playlistDelegate
		playlistDataSource!.onAddToPlaylistHandler = { [weak self] completion in
			guard let self = self else {
				return
			}
			
			self.addToPlaylistCompletion = completion
			self.performSegue(withIdentifier: Segues.choosePlaylist, sender: self)
		}
		
		collectionViewHelper = MusicListDisplayHelper(dataSources: [playlistDataSource!],
													  viewController: self,
													  collectionView: collectionView!,
													  dragAllowed: false,
													  countUpdater: { [weak self] numberOfItems in
														guard let self = self else {
															return
														}
														self.emptyView?.alpha =
															self.playlistDataSource!.numberOfItems() == 0 ? 1.0 : 0.0
														self.updatePlayAllButtonText(count: numberOfItems)
			},
													  onItemSelected: { [weak self] indexPath, item in
														guard let self = self else {
															return
														}
														self.didSelect(row: indexPath.row, item: item)
														
		})
	}
	
	private func didSelect(row: Int, item: MusicListDisplayHelperItem) {
	}
}

// MARK:- MusicLibraryViewControllerDelegate Conformance
extension PlaylistSongsViewController: MusicLibraryViewControllerDelegate {
	func allMediaItems() -> [IoTMediaItem] {
		return playlist?.items ?? []
	}
	
	func optionsForButton() -> [String] {
		let options = [MusicLibraryOptions.playNow.toString(),
					   MusicLibraryOptions.playNext.toString(),
					   MusicLibraryOptions.addToQueue.toString(),
					   MusicLibraryOptions.editPlaylistName.toString(),
					   MusicLibraryOptions.clearPlaylist.toString(),
					   MusicLibraryOptions.deletePlaylist.toString()]
		return options
	}
	
	func doOption(_ option: MusicLibraryOptions) -> Bool {
		var handled = false
		switch option {
		case .editPlaylistName:
			playlistHelper.editPlaylistName(playlist: playlist!,
											completion: { [weak self] playlistOpt in
												guard let playlist = playlistOpt,
													let self = self else {
														return
												}
												self.title = playlist.name.uppercased()
			})
			handled = true
		case .clearPlaylist:
			showDestructiveAlert(message: NSLocalizedString("Are you sure you want to remove all songs from this list?\n\nNote: Songs will NOT be deleted from your device.", comment: "Alert message"),
								 destructiveOption: NSLocalizedString("Clear Playlist", comment: "Alert option"),
								 destructiveAction: {
									self.playlist!.items = []
									UserPlaylistsController.sharedInstance.updateUserPlaylist(self.playlist!)
									self.playlistDelegate!.forceReload()
			})
			handled = true
		case .deletePlaylist:
			showDestructiveAlert(message: NSLocalizedString("Are you sure you want to delete this playlist?\n\nNote: Songs will NOT be deleted from your device.", comment: "Alert message"),
								 destructiveOption: NSLocalizedString("Delete Playlist", comment: "Alert option"),
								 destructiveAction: {
									UserPlaylistsController.sharedInstance.removeUserPlaylist(self.playlist!)
									self.performSegue(withIdentifier: Segues.dismiss, sender: self)
									
			})
			handled = true
		default:
			break
		}
		return handled
	}
}


