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

import UIKit
import CocoaLumberjack

class NewUserPlaylistHelper {
    typealias MediaProvider = (_ completion: @escaping ([IoTMediaItem])->()) -> ()
	typealias CompletionHandler = (UserPlaylist?) -> ()
	
	private weak var viewController: UIViewController?
	private let mediaItemProvider: MediaProvider
	private var onCompletion: CompletionHandler?
	
	// reference maintained for access to "Save" field in create playlist dialog
	private weak var playlistCreateSaveAction: UIAlertAction?
	
	init(viewController: UIViewController,
		 mediaItemProvider:  @escaping MediaProvider) {
		self.viewController = viewController
		self.mediaItemProvider = mediaItemProvider
	}
}

// MARK: - Public Methods
extension NewUserPlaylistHelper {
	func saveAsPlaylist(completion: CompletionHandler?) {
		showPlaylistNameDialog(title: NSLocalizedString("New Playlist", comment: "Confirmation dialog"),
							   message: NSLocalizedString("Please enter name for new playlist", comment: "Confirmation dialog"),
							   playlist: nil,
							   completion: completion)
	}
	
	func editPlaylistName(playlist: UserPlaylist,
						  completion: CompletionHandler?) {
		showPlaylistNameDialog(title: NSLocalizedString("Edit Playlist Name", comment: "Confirmation dialog"),
							   message: NSLocalizedString("Please enter new name for playlist", comment: "Confirmation dialog"),
							   playlist: playlist,
							   completion: completion)
	}
}

// MARK: - Private Methods
extension NewUserPlaylistHelper {
	private func showPlaylistNameDialog(title: String,
										message: String,
										playlist: UserPlaylist?,
										completion: CompletionHandler?) {
		onCompletion = completion
		let alertController = UIAlertController(title: title,
												message: message,
												preferredStyle: .alert)
		
		alertController.addTextField { textField in
			textField.placeholder = NSLocalizedString("Playlist Name", comment: "Text Field Placeholder")
			textField.addTarget(self, action: #selector(self.playlistCreateTextDidChange(_:)), for: .editingChanged)
		}
        
        let saveAction = UIAlertAction(title: NSLocalizedString("Save", comment: "Confirmation dialog"),
                                       style: .default,
                                       handler: { action in
                                        guard let textField = alertController.textFields?.first,
                                            let newName = textField.text else {
                                                return
                                        }
                                        
                                        if let existing = playlist {
                                            existing.name = newName
                                            UserPlaylistsController.sharedInstance.updateUserPlaylist(existing)
                                            self.complete(playlist: playlist)
                                        } else {
                                            self.createPlaylist(name: newName)
                                        }
        })
        saveAction.isEnabled = false // Disabled as no text - we enable as it is edited
        alertController.addAction(saveAction)
        playlistCreateSaveAction = saveAction
        
        alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel"),
                                                style: .cancel,
												handler: { action in
													self.complete(playlist: playlist)
		}))
		
		viewController?.present(alertController, animated: true, completion: nil)
	}
	
	@objc private func playlistCreateTextDidChange(_ sender: UITextField?) {
		guard let textField = sender,
			let text = textField.text else {
				playlistCreateSaveAction?.isEnabled = false
				return
		}
		
		if text.count == 0 {
			playlistCreateSaveAction?.isEnabled = false
			return
		}
		
		playlistCreateSaveAction?.isEnabled = !UserPlaylistsController.sharedInstance.playlistExists(forName: text)
	}
	
	private func createPlaylist(name: String) {
        mediaItemProvider({ [weak self] (items) in
            guard let self = self else {
                return
            }

            do {
                let playlist = try UserPlaylistsController.sharedInstance.createUserPlaylist(name: name, items: items)
                self.complete(playlist: playlist)
            } catch let error {
                DDLogError("Could not create playlist: \(name) reason: \(error)")
                self.complete(playlist: nil)
            }
        })
	}
	
	private func complete(playlist: UserPlaylist?) {
		if let closure = onCompletion {
			closure(playlist)
		}
	}
}
