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

import Foundation

protocol IoTPlayerGroupDisplayable {
    var groupID: String { get }
    var isConvenienceGroup: Bool { get }
    var displayName: String { get }
    var playlist: IoTPlaylist? { get }
    var available: Bool { get }
    var members: [IoTPlayerGroupMember] { get }
}

// Make IoTPlayerGroup conform
extension IoTPlayerGroup: IoTPlayerGroupDisplayable {}

// Used for UI testing
struct DummyIoTPlayerGroup: IoTPlayerGroupDisplayable {
    var groupID: String
    var isConvenienceGroup: Bool
    var displayName: String
    var playlist: IoTPlaylist?
    var available: Bool
    var members: [IoTPlayerGroupMember]
}

class PlayerGroupDisplayableWrapper: NSObject, MasterViewControllerDisplayable {
    weak var parent: MasterViewControllerDisplayable? = nil
    let children: [MasterViewControllerDisplayable]
    let depth: UInt

    let playerGroup: IoTPlayerGroupDisplayable

    // Convenience group helpers.
    let hasBTChildren: Bool
    let hasZBChildren: Bool
    
    init(playerGroup: IoTPlayerGroupDisplayable,
         depth: UInt,
         children: [MasterViewControllerDisplayable],
         hasBTChildren: Bool,
         hasZBChildren: Bool) {
        self.playerGroup = playerGroup
        self.depth = depth
        self.children = children
        self.hasBTChildren = hasBTChildren
        self.hasZBChildren = hasZBChildren
    }

    var id: String {
        return "GP:" + playerGroup.groupID
    }

    var name: String {
        if playerGroup.isConvenienceGroup {
            return playerGroup.displayName
        } else {
            return playerGroup.displayName + ": " +
                (NSString.localizedStringWithFormat("%ld DEVICES", playerGroup.members.count) as String)
        }
    }

    var available: Bool {
        return playerGroup.available
    }

    var stateDescription: [String] {
        if let currentItem = playerGroup.playlist?.currentItem,
            !currentItem.isEmpty {
            let trackName = currentItem.title
            let artist = currentItem.artist
            return [trackName, artist]
        } else {
            if playerGroup.available || playerGroup.members.count == 0 {
                return []
            } else {
                return [NSLocalizedString("Devices Unavailable", comment: "Devices Unavailable - main screen group cell")]
            }
        }
    }

    var encapsulatedType: MasterViewControllerDisplayableType {
        return playerGroup.isConvenienceGroup ? .speakerConvenienceGroup : .speakerGroup
    }
}
