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

import UIKit
import CocoaLumberjack

class InputSourcesOutputSinksMusicListDisplayHelperItem : MusicListDisplayHelperItem {
	public private(set) var player: IoTPlayer
	public private(set) var source: IoTInputOutputSelector
	
    init(source: IoTInputOutputSelector, player: IoTPlayer, isActive: Bool, isOnlyPlayer: Bool) {
		self.player = player
		self.source = source
		super.init()
		
		self.state = .available
        self.title = isOnlyPlayer ? source.name : player.displayName + " - " + source.name
		self.subtitle = ""
		self.accessory = isActive ? .checked : .unchecked
		self.options = []
	}
}

// MARK: -

class InputSourcesDataSourceDelegate {
	private let playerGroup: IoTPlayerGroup
    private let playerController: PlayerControllerProtocol
	var onItemsInvalidated: (() -> ())?
	
    init (playerGroup: IoTPlayerGroup, playerController: PlayerControllerProtocol) {
		self.playerGroup = playerGroup
        self.playerController = playerController
	}
}

// MARK: - Public Methods
extension InputSourcesDataSourceDelegate {
	func forceReload() {
		if let handler = onItemsInvalidated {
			handler()
		}
	}
}

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

    func itemsInitialState(completion: @escaping ([MusicListDisplayHelperItem]) -> () , completionQueue: DispatchQueue) -> () {
        var array = [MusicListDisplayHelperItem]()
        let activeSelector = playerGroup.activeInputSelector
        playerGroup.members.forEach { member in
            if let player = playerController.player(id: member.playerID),
                player.isInputSelectorModeSupported {
                let selectors = player.inputSelectors
                selectors.forEach({ selector in
                    array.append(InputSourcesOutputSinksMusicListDisplayHelperItem(source: selector,
                                                                                   player: player,
                                                                                   isActive: selector.identifier == activeSelector?.identifier,
                                                                                   isOnlyPlayer: playerGroup.isConvenienceGroup))
                })
            }
        }

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