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

import UIKit
import CocoaLumberjack

class SongsMusicListDisplayHelperItem : MusicListDisplayHelperItem {
	public private(set) var libraryObject: MusicLibrarySong
	
	init(song: MusicLibrarySong,
		 accessory: MusicListDisplayHelperItemAccessory,
		 options: [String]) {
		self.libraryObject = song
		
		super.init()
		self.state = song.hasDRM ? .unplayable : .available
		self.imageURL = HTTPServer.sharedInstance.urlForLocalAsset(id: song.id, type: .artwork)
		self.title = song.title
		var st = song.artist
		if !st.isEmpty && !song.album.isEmpty {
			st = st + " - "
		}
		st = st + song.album
		self.subtitle = st
		self.accessory = accessory
		self.options = options
	}
}

// MARK: -

class SongsDataSourceDelegate {
	private(set) var songs: [MusicLibrarySong]
	var onItemsInvalidated: (() -> ())?
	
	init(songs: [MusicLibrarySong]) {
		self.songs = songs
	}
}

// MARK: - Public Methods
extension SongsDataSourceDelegate {
	func forceReload(songs newSongs: [MusicLibrarySong]) {
		songs = newSongs
		if let handler = onItemsInvalidated {
			handler()
		}
	}
}

// MARK: - MusicListDataSourceDelegate Conformance
extension SongsDataSourceDelegate: MusicListDataSourceDelegate {
	var title: String {
		return NSLocalizedString("Songs", comment: "Songs Title")
	}

    func itemsInitialState(completion: @escaping ([MusicListDisplayHelperItem]) -> () , completionQueue: DispatchQueue) -> () {
        let count = songs.count
        var array = [MusicListDisplayHelperItem]()
        array.reserveCapacity(count)
        for i in 0..<count {
            array.append(SongsMusicListDisplayHelperItem(song: songs[i],
                                                         accessory: .options,
                                                         options: []))
        }

        completionQueue.async {
            completion(array)
        }
    }
	
	func accessoryForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> MusicListDisplayHelperItemAccessory {
		return item.state == .unplayable ?  .none : .options
	}
	
	func mediaItemForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> IoTMediaItem? {
		if let songItem = item as? SongsMusicListDisplayHelperItem {
			return LocalMusicLibrary.sharedInstance.mediaItemForSong(songItem.libraryObject)
		}
		return nil
	}
	
	func optionsForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> [String] {
		var options = [MusicLibraryItemOptions.playNow.toString(),
					   MusicLibraryItemOptions.playNext.toString(),
					   MusicLibraryItemOptions.addToQueue.toString()]
		
		if let mediaItem = mediaItemForItem(item, atIndex: index) {
			
			if !FavoritesController.sharedInstance.isFavorite(item: mediaItem) {
				options.append(MusicLibraryItemOptions.addToFavorites.toString())
			}
		}
		
		options.append(MusicLibraryItemOptions.addToPlaylist.toString())
		return options
	}
}
