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

import UIKit
import CocoaLumberjack

class GenresMusicListDisplayHelperItem : MusicListDisplayHelperItem {
	public private(set) var libraryObject: MusicLibraryGenre

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

// MARK: -

class GenresDataSourceDelegate {
	var onItemsInvalidated: (() -> ())?
	
	private(set) var genres: [MusicLibraryGenre]
	
	init(genres: [MusicLibraryGenre]) {
		self.genres = genres
	}
}

// MARK: - Public Methods
extension GenresDataSourceDelegate {
	func forceReload(genres newGenres: [MusicLibraryGenre]) {
		genres = newGenres
		if let handler = onItemsInvalidated {
			handler()
		}
	}
}

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

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