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

import UIKit
import CocoaLumberjack

protocol DeviceDetailViewControllerProvider: UITableViewDelegate, UITableViewDataSource {
    var representativeImage: UIImage? { get }
    var deviceModel: String? { get }
    var deviceManufacturer: String? { get }
    var connectivity: DeviceConnectivityInfo? { get }
}

class DeviceDetailTableViewCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel?
}

class DeviceDetailGroupingTableViewCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel?
    @IBOutlet weak var membersStackView: UIStackView?
}

class DeviceDetailViewController: MiniPlayerEmbeddingViewController {
    struct Segues {
        static let showAudioSources = "showAudioSources"
        static let showOutputSinks = "showOutputSinks"
        static let showSpeakerGrouping = "showSpeakerGrouping"
        static let showSurroundSound = "showSurroundSound"
    }

	@IBOutlet private weak var tableView: UITableView?
    @IBOutlet private weak var imageView: UIImageView?
    @IBOutlet private weak var manufacturerNameLabel: UILabel?
    @IBOutlet private weak var deviceNameLabel: UILabel?

    @IBOutlet private weak var btIcon: UIImageView?
    @IBOutlet private weak var zigbeeIcon: UIImageView?
    @IBOutlet private weak var wifiIcon: UIImageView?

    @IBOutlet private weak var avsVoiceUIIcon: UIImageView?
    @IBOutlet private weak var gvaVoiceUIIcon: UIImageView?
	@IBOutlet private weak var cortanaVoiceUIIcon: UIImageView?
    @IBOutlet private weak var modularVoiceUIIcon: UIImageView?

    @IBOutlet private weak var connectivityViewHeightConstraint: NSLayoutConstraint?
    private let collapsedConnectivityViewHeight: CGFloat = 0.0
    private let expandedConnectivityViewHeight: CGFloat = 28.0

    var provider: DeviceDetailViewControllerProvider?
    var item: MasterViewControllerDisplayable?

    override func viewDidLoad() {
        hasSearchButton = false
        super.viewDidLoad()
        setUpUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        if let _ = provider as? SpeakerGroupDetailViewProvider {
            title = playerGroup?.displayName.uppercased()
        } else if let speakerProvider = provider as? SpeakerDetailViewProvider,
            let player = playerController.player(id: speakerProvider.playerID) {
            title = player.displayName.uppercased()
        }
        tableView?.reloadData()
		imageView?.image = provider?.representativeImage
        if let manufacturer = provider?.deviceManufacturer {
            manufacturerNameLabel?.text = manufacturer.uppercased()
            manufacturerNameLabel?.isHidden = false
        } else {
             manufacturerNameLabel?.isHidden = true
        }

        if let name = provider?.deviceModel {
            deviceNameLabel?.text = name.uppercased()
            deviceNameLabel?.isHidden = false
        } else {
            deviceNameLabel?.isHidden = true
        }

        let connectivity = provider?.connectivity ??
            DeviceConnectivityInfo.allMissing()

        connectivityViewHeightConstraint?.constant = connectivity.anyPresent() ?
            expandedConnectivityViewHeight : collapsedConnectivityViewHeight

        btIcon?.isHidden = connectivity.bluetooth == .missing
        btIcon?.image = connectivity.bluetooth == .enabled ? UIImage(named: "ic-bluetooth-connected") : UIImage(named: "ic-bluetooth")

        zigbeeIcon?.isHidden = connectivity.zigbee == .missing
        zigbeeIcon?.image = connectivity.zigbee == .enabled ? UIImage(named: "ic-zigbee-connected") : UIImage(named: "ic-zigbee")

        wifiIcon?.isHidden = connectivity.wifi == .missing
        wifiIcon?.image = connectivity.wifi == .enabled ? UIImage(named: "ic-wifi-connected") : UIImage(named: "ic-wifi")

    	avsVoiceUIIcon?.isHidden = connectivity.avsVoiceUI != .enabled
		gvaVoiceUIIcon?.isHidden = connectivity.gvaVoiceUI != .enabled
        cortanaVoiceUIIcon?.isHidden = connectivity.cortanaVoiceUI != .enabled
        modularVoiceUIIcon?.isHidden = connectivity.modularVoiceUI != .enabled
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        segue.destination.injectDependencies(preferences: preferences,
                                             playerController: playerController)
        if let embedding = segue.destination as? MiniPlayerEmbeddingViewController {
            embedding.playerGroup = playerGroup
        }

        if let surroundVC = segue.destination as? SpeakerSetUpMenuViewController,
            let spkrProvider = provider as? SpeakerDetailViewProvider,
            let player = playerController.player(id: spkrProvider.playerID),
            let device = playerController.device(player: player) {
            surroundVC.deviceID = device.deviceID
        }
    }
}

extension DeviceDetailViewController {
    private func setUpUI() {
        if let currentItem = item {
            switch currentItem.encapsulatedType {
            case .speakerGroup:
                if let group = playerGroup {
                    provider = SpeakerGroupDetailViewProvider(tableView: tableView,
                                                              parentVC: self,
                                                              playerGroup:group,
                                                              playerController: playerController)
                    tableView?.delegate = provider!
                    tableView?.dataSource = provider!

                    title = group.displayName.uppercased()
                }
            case .speakerConvenienceGroup:
                // Convenience groups are just a wrapper around an ungrouped speaker.
                if let group = playerGroup,
                    group.isConvenienceGroup,
                    let leadID = group.members.first?.playerID {
                    provider = SpeakerDetailViewProvider(tableView: tableView,
                                                         parentVC: self,
                                                         playerID: leadID,
                                                         isGrouped: false, // not in a real group.
                                                         playerController: playerController)
                    tableView?.delegate = provider!
                    tableView?.dataSource = provider!

                    if let player = playerController.player(id: leadID) {
                        title = player.displayName.uppercased()
                    }
                }
            case .speaker:
                if let playerItem = currentItem as? PlayerDisplayableWrapper {
                    provider = SpeakerDetailViewProvider(tableView: tableView,
                                                         parentVC: self,
                                                         playerID: playerItem.playerID,
                                                         isGrouped: true,
                                                         playerController: playerController)
                    tableView?.delegate = provider!
                    tableView?.dataSource = provider!

                    if let player = playerController.player(id: playerItem.playerID) {
                        title = player.displayName.uppercased()
                    }
                }
            default:
                tableView?.dataSource = self
                tableView?.delegate = self
            }
        } else {
            tableView?.dataSource = self
            tableView?.delegate = self
        }
    }
}

extension DeviceDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		return UITableViewCell()
    }
}
