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

import UIKit
import Kingfisher
import CocoaLumberjack

class ScrollingFavoritesTableViewCell: UITableViewCell {
	typealias FavoriteSelectedHandler = (IoTMediaItem) -> ()
	// MARK: Public Properties
	let collectionViewCellIdentifier = "ScrollingFavoritesCollectionViewCell"
	lazy var favorites: [IoTMediaItem] = {
		return FavoritesController.sharedInstance.allFavorites
	} ()
	var onFavoriteSelected: FavoriteSelectedHandler?
	var onShowAll: (() -> ())?
	
	// MARK: UI Outlets
	@IBOutlet weak var collectionView: UICollectionView?
	@IBOutlet weak var showAllButton: UIButton?
}

// MARK: - Overridden Methods
extension ScrollingFavoritesTableViewCell {
	override func prepareForReuse() {
		favorites = FavoritesController.sharedInstance.allFavorites
		collectionView?.reloadSections([0])
	}
}

// MARK: - UI Actions
extension ScrollingFavoritesTableViewCell {
	@IBAction private func showAllTapped(_ sender: UIButton) {
		guard let handler = onShowAll else {
			return
		}
		handler()
	}
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate Conformance
extension ScrollingFavoritesTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
	func numberOfSections(in collectionView: UICollectionView) -> Int {
		return 1
	}
	
	func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
		return favorites.count
	}
	
	func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
		DDLogVerbose("Selected \(indexPath.row)")
		guard let handler = onFavoriteSelected else {
			return
		}
		handler(favorites[indexPath.row])
	}
	
	func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
		var cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellIdentifier, for: indexPath) as? ScrollingFavoritesCollectionViewCell
		if cell == nil {
			cell = ScrollingFavoritesCollectionViewCell()
		}
		
		let item = favorites[indexPath.row]
		cell?.albumArtworkImageView?.kf.setImage(with: URL(string: item.thumbnailURL),
												 placeholder: UIImage(named: "album-art-default-med"))
		cell?.artistLabel?.text = item.artist
		cell?.titleLabel?.text = item.title

        cell?.makeAccessible(item.title + " " + item.artist, doNotLocalizeForHuman: true)
		
		return cell!
	}
}
