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

import UIKit
import CocoaLumberjack

class AlbumsMusicListDisplayHelperItem : MusicListDisplayHelperItem {

	public private(set) var libraryObject: MusicLibraryAlbum
	
	init(album: MusicLibraryAlbum,
		 accessory: MusicListDisplayHelperItemAccessory,
		 options: [String]) {
		self.libraryObject = album
		super.init()
		
		self.state = .available
		self.imageURL = HTTPServer.sharedInstance.urlForLocalAsset(id: album.representativeSongID, type: .artwork)
		self.title = album.title
		// Pluralisation of string below to be handled elsewhere
		self.subtitle = String.localizedStringWithFormat("%d Songs", album.numberOfSongs)
		self.accessory = accessory
		self.options = options
	}
}

// MARK: -

class AlbumsDataSourceDelegate {
	private(set) var albums: [MusicLibraryAlbum]
	var onItemsInvalidated: (() -> ())?
	var title: String { return NSLocalizedString("Albums", comment: "Albums Title") }
	
	init(albums: [MusicLibraryAlbum]) {
		self.albums = albums
	}
}

// MARK: - Public Methods
extension AlbumsDataSourceDelegate {
	func forceReload(albums newAlbums: [MusicLibraryAlbum]) {
		albums = newAlbums
		if let handler = onItemsInvalidated {
			handler()
		}
	}
}

// MARK: - MusicListDataSourceDelegate Conformance
extension AlbumsDataSourceDelegate: MusicListDataSourceDelegate {
    func itemsInitialState(completion: @escaping ([MusicListDisplayHelperItem]) -> () , completionQueue: DispatchQueue) -> () {
        let count = albums.count
        var array = [MusicListDisplayHelperItem]()
        array.reserveCapacity(count)
        for i in 0..<count {
            array.append(AlbumsMusicListDisplayHelperItem(album: albums[i],
                                                          accessory: .none,
                                                          options: []))
        }

        completionQueue.async {
            completion(array)
        }
    }
	
	func accessoryForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> MusicListDisplayHelperItemAccessory {
		return .none
	}
	
	func mediaItemForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> IoTMediaItem? {
		return nil
	}
	
	func optionsForItem(_ item: MusicListDisplayHelperItem, atIndex index: Int) -> [String] {
		return []
	}
}

