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

import UIKit
import CocoaLumberjack

class ArtistsMusicListDisplayHelperItem : MusicListDisplayHelperItem {

	public private(set) var libraryObject: MusicLibraryArtist

	init(artist: MusicLibraryArtist,
		 accessory: MusicListDisplayHelperItemAccessory,
		 options: [String]) {
		self.libraryObject = artist
		super.init()
		
		self.state = .available
		self.imageURL = HTTPServer.sharedInstance.urlForLocalAsset(id: artist.representativeSongID, type: .artwork)
		self.title = artist.name
		// Pluralisation of string below to be handled elsewhere
		let albumText = String.localizedStringWithFormat("%d Albums", artist.numberOfAlbums)
		let songText = String.localizedStringWithFormat("%d Songs", artist.numberOfSongs)
		self.subtitle = albumText + ", " + songText
		self.accessory = accessory
		self.options = options
	}
}

// MARK: -

class ArtistsDataSourceDelegate {
	private(set) var artists: [MusicLibraryArtist]
	var onItemsInvalidated: (() -> ())?
	
	init(artists: [MusicLibraryArtist]) {
		self.artists = artists
	}
}

// MARK: - Public Methods
extension ArtistsDataSourceDelegate {
	func forceReload(artists newArtists: [MusicLibraryArtist]) {
		artists = newArtists
		if let handler = onItemsInvalidated {
			handler()
		}
	}
}

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

    func itemsInitialState(completion: @escaping ([MusicListDisplayHelperItem]) -> () , completionQueue: DispatchQueue) -> () {
        let count = artists.count
        var array = [MusicListDisplayHelperItem]()
        array.reserveCapacity(count)
        for i in 0..<count {
            array.append(ArtistsMusicListDisplayHelperItem(artist: artists[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 []
	}
}
