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

import UIKit
import CocoaLumberjack

class OutputSinksDataSourceDelegate {
    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 OutputSinksDataSourceDelegate {
    func forceReload() {
        if let handler = onItemsInvalidated {
            handler()
        }
    }
}

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

    func itemsInitialState(completion: @escaping ([MusicListDisplayHelperItem]) -> () , completionQueue: DispatchQueue) -> () {
        var array = [MusicListDisplayHelperItem]()
        let activeSelectorsForGroup = playerGroup.activeOutputSelectors
        playerGroup.members.forEach { member in
            if let player = playerController.player(id: member.playerID),
                player.isOutputSelectorModeSupported {
                let selectors = player.outputSelectors
                selectors.forEach({ selector in
					let active = activeSelectorsForGroup.contains(selector)
                    array.append(InputSourcesOutputSinksMusicListDisplayHelperItem(source: selector,
                                                                                   player: player,
                                                                                   isActive: active,
                                                                                   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 []
    }
}

