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

/*
import UIKit
import CocoaLumberjack

class SettingsMasterViewController: ModalTableViewController {
	// MARK: Private Types
	private struct Segues {
		static let showSpeakerSettings = "showSpeakerSettings"
	}
	
	private enum SectionType {
		case speakers
		case general
	}
	
	private enum RowType {
		case speakerNoUpdate
		case speakerHasFirmware
		case speakerUpdating
		case speakerUpdateAttemptedFailed
		case speakerUpdateAttemptedSuccessful
		case updateAll
		case reset
	}
	
	private struct Section {
		let type: SectionType
		let title: String
		let rows: [Row]
	}
	
	private struct Row {
		let type: RowType
		let title: String
		let subtitle: String?
		let additionalText: String?
	}
	// MARK: Private Properties
	private var sections = [Section] ()
	private var observers = [ObserverToken] ()
	private var players = [IoTPlayer] ()
	private let tableViewHeaderHeight: CGFloat = 38.0
}

// MARK: - Overridden Methods
extension SettingsMasterViewController {
	override func viewDidLoad() {
		title = NSLocalizedString("SETTINGS", comment: "Settings Title")
		
		super.viewDidLoad()
		
		let nib1 = UINib(nibName: SettingsOneRowTableViewCell.reuseIdentifier, bundle: nil)
		tableView?.register(nib1, forCellReuseIdentifier: SettingsOneRowTableViewCell.reuseIdentifier)
		
		let nib2 = UINib(nibName: SettingsTwoRowTableViewCell.reuseIdentifier, bundle: nil)
		tableView?.register(nib2, forCellReuseIdentifier: SettingsTwoRowTableViewCell.reuseIdentifier)
		
		let nib3 = UINib(nibName: SettingsUpdatingFirmwareTableViewCell.reuseIdentifier, bundle: nil)
		tableView?.register(nib3, forCellReuseIdentifier: SettingsUpdatingFirmwareTableViewCell.reuseIdentifier)
		
		let nib = UINib(nibName: SettingsTableViewHeaderView.reuseIdentifier, bundle: nil)
		tableView?.register(nib, forHeaderFooterViewReuseIdentifier: SettingsTableViewHeaderView.reuseIdentifier)

		// Accessibility
		tableView?.accessibilityLabel = "Speaker Master List"
	}
	
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		
		let deviceHandler: (DeviceNotification) -> () = { [weak self] notification in
			guard let self = self else { return }
			
			if notification.reason == .added ||
				notification.reason == .removed ||
				notification.reason == .updateAvailable ||
                notification.reason == .updateStarted ||
                notification.reason == .autoUpdateChanged ||
                notification.reason == .updateProgressChanged ||
                notification.reason == .updateStatusChanged {
                self.reloadState()
            }
        }

        let deviceObserver = NotificationCenter.default.addObserver(forType: DeviceNotification.self,
                                                                    object: playerController,
                                                                    queue: OperationQueue.main,
                                                                    using: deviceHandler)
        // ************


        let homeTheaterHandler: (HomeTheaterNotification) -> () = { [weak self] notification in
            guard let self = self else { return }

            if notification.reason == .firmwareUpdateAvailable ||
                notification.reason == .firmwareUpdateStatusChanged ||
                notification.reason == .firmwareAutoUpdateChanged ||
                notification.reason == .firmwareUpdateProgressChanged {
                DDLogVerbose("REASON: \(notification.reason)")
                self.reloadState()
            }
        }

        let homeTheaterObserver = NotificationCenter.default.addObserver(forType: HomeTheaterNotification.self,
                                                                         object: playerController,
                                                                         queue: OperationQueue.main,
                                                                         using: homeTheaterHandler)

        observers = [deviceObserver, homeTheaterObserver]

		if APIAvailability.sharedInstance.firmwareAPIAvailable {
			let devices = playerController.devices
			FirmwareOperationsHelper.sharedInstance.checkForAnyNewFirmware(devices: devices, controller: playerController)
		}
		
		reloadState()
	}
	
	override func viewDidDisappear(_ animated: Bool) {
		super.viewDidDisappear(animated)
		
		observers.forEach { NotificationCenter.default.removeObserver($0) }
		observers = []
	}
	
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch segue.identifier! {
        case Segues.showSpeakerSettings:
            if let speakerVC = segue.destination as? SpeakerSettingsViewController,
                let player = sender as? IoTPlayer,
                let device = playerController.device(player: player) {
                speakerVC.deviceID = device.deviceID
                speakerVC.injectDependencies(preferences: preferences, playerController: playerController)
                navigationItem.backBarButtonItem?.accessibilityIdentifier = "Modal Back"
                navigationItem.backBarButtonItem?.accessibilityLabel = "Modal Back"
            }
        default:
			break
		}
	}
}

// MARK: - Overridden UITableViewViewController Methods
extension SettingsMasterViewController {
	override func numberOfSections(in tableView: UITableView) -> Int {
		return sections.count
	}
	
	override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return sections[section].rows.count
	}
	
	override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		let row = sections[indexPath.section].rows[indexPath.row]
		if row.type == .speakerHasFirmware || row.type == .speakerUpdateAttemptedFailed || row.type == .speakerUpdateAttemptedSuccessful {
			var cell = tableView.dequeueReusableCell(withIdentifier: SettingsTwoRowTableViewCell.reuseIdentifier, for: indexPath) as? SettingsTwoRowTableViewCell
			if cell == nil {
				cell = SettingsTwoRowTableViewCell()
			}
			cell?.titleLabel?.text = row.title
			cell?.subtitleLabel?.text = row.subtitle
//			cell?.alertButton?.isHidden = false
			cell?.accessibilityLabel = row.title
			cell?.accessoryType = .disclosureIndicator
			if row.type != .speakerUpdateAttemptedSuccessful {
/*				cell?.onTapAlertButton = { [weak self] updaterCell in
					if let self = self,
						let ip = self.tableView.indexPath(for: updaterCell) {
						let player = self.players[ip.row]
						if let _ = self.playerController.device(player: player) {
							FirmwareOperationsHelper.sharedInstance.beginInteractiveFirmwareUpdate(viewController: self,
																								   deviceID: player.playerID,
																								   controller: self.playerController,
																								   preferences: self.preferences)
						}
					}
				}
 */
			} else {
//				cell?.onTapAlertButton = nil
			}
			return cell!
		} else if row.type == .speakerUpdating {
			var cell = tableView.dequeueReusableCell(withIdentifier: SettingsUpdatingFirmwareTableViewCell.reuseIdentifier, for: indexPath) as? SettingsUpdatingFirmwareTableViewCell
			if cell == nil {
				cell = SettingsUpdatingFirmwareTableViewCell()
			}
			cell?.titleLabel?.text = row.title
			cell?.accessibilityLabel = row.title
			cell?.subtitleLabel?.text = row.subtitle
			cell?.progressLabel?.text = row.additionalText
			cell?.accessoryType = .disclosureIndicator
			return cell!
		} else {
			
			var cell = tableView.dequeueReusableCell(withIdentifier: SettingsOneRowTableViewCell.reuseIdentifier, for: indexPath) as? SettingsOneRowTableViewCell
			if cell == nil {
				cell = SettingsOneRowTableViewCell()
			}
			
			if row.type == .speakerNoUpdate {
				cell?.style = .plain
				cell?.selectionStyle = .gray
				cell?.accessoryType = .disclosureIndicator
			} else {
				cell?.style = .plain
				cell?.selectionStyle = .gray
				cell?.accessoryType = .none
			}
			
			cell?.titleLabel?.text = row.title
			cell?.accessibilityIdentifier = row.title
			cell?.accessibilityLabel = row.title
			return cell!
		}
	}
	
	override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		tableView.deselectRow(at: indexPath, animated: false)
		let row = sections[indexPath.section].rows[indexPath.row]
		
		switch row.type {
		case .updateAll:
			let devices = playerController.devices
			FirmwareOperationsHelper.sharedInstance.updateDevicesIfPossible(devices,
																			controller: playerController,
																			requireAutoUpdate: false)
			break
		case .speakerHasFirmware,
			 .speakerNoUpdate,
			 .speakerUpdating,
			 .speakerUpdateAttemptedFailed,
			 .speakerUpdateAttemptedSuccessful:
			let player = players[indexPath.row]
			performSegue(withIdentifier: Segues.showSpeakerSettings, sender: player)
			break
		case .reset:
			break
		}
	}
	
	override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
		let _ = sections[indexPath.section].rows[indexPath.row]

		return indexPath
	}
	
	override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
		return tableViewHeaderHeight
	}
	
	override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
		return CGFloat.leastNormalMagnitude // if we return zero it gets ignored.
	}
	
	override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
		guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: SettingsTableViewHeaderView.reuseIdentifier) as? SettingsTableViewHeaderView else {
			return nil
		}
		
		header.titleLabel?.text = sections[section].title
		return header
	}
	
	override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
		// Return false if you do not want the specified item to be editable.
		return false
	}
}

// MARK: - Private Methods
extension SettingsMasterViewController {
	private func reloadState() {
		var newSections = [Section] ()

		// If we've found any autoupdate devices then start updates for them
		let devices = playerController.devices
		FirmwareOperationsHelper.sharedInstance.updateDevicesIfPossible(devices,
																		controller: playerController,
																		requireAutoUpdate: true)
		
		players = playerController.players.sorted(by: { $0.homeTheaterDisplayName < $1.homeTheaterDisplayName })
		
		if players.count > 0 {
			var anyUpdates = false
			var rows = players.compactMap { player -> SettingsMasterViewController.Row? in
				if let device = playerController.device(player: player) {
					let updateStatus = APIAvailability.sharedInstance.firmwareAPIAvailable ?
						device.updateStatus : .none
					DDLogVerbose("Update Status for \(device.displayName) is \(updateStatus)")
					if updateStatus == .updating {
						let additionalText = device.isFirmwareUpdateProgressSupported ? "\(device.firmwareUpdateProgress) %" : ""
						return Row(type: .speakerUpdating,
								   title: player.homeTheaterDisplayName,
								   subtitle: NSLocalizedString("Firmware update in progress", comment: "Firmware update TV Row"),
								   additionalText: additionalText)
					} else if updateStatus == .none {
						if APIAvailability.sharedInstance.firmwareAPIAvailable &&
							FirmwareOperationsHelper.sharedInstance.isFirmwareUpdateAvailable(device: device, controller: playerController) {
							anyUpdates = true
							return Row(type: .speakerHasFirmware,
									   title: player.homeTheaterDisplayName,
									   subtitle: NSLocalizedString("Firmware update available", comment: "Firmware update TV Row"),
									   additionalText: nil)
						} else {
							return Row(type: .speakerNoUpdate,
									   title: player.homeTheaterDisplayName,
									   subtitle: nil,
									   additionalText: nil)
						}
					} else {
						// An update was attempted but something happened
						var subtitle = ""
						var rowType: RowType = .speakerUpdateAttemptedFailed
						switch updateStatus {
						case .failed:
							subtitle = NSLocalizedString("Firmware update failed", comment: "Firmware update TV Row")
						case .notNeeded:
							subtitle = NSLocalizedString("Firmware update not needed", comment: "Firmware update TV Row")
						case .lowBattery:
							subtitle = NSLocalizedString("Battery too low for firmware update", comment: "Firmware update TV Row")
						case .successful:
							rowType = .speakerUpdateAttemptedSuccessful
							if device.physicalRebootRequired {
								subtitle = NSLocalizedString("Physical reboot required", comment: "Firmware update TV Row")
							} else {
								subtitle = NSLocalizedString("Firmware update successful", comment: "Firmware update TV Row")
							}
						default:
							break
						}
						return Row(type: rowType,
								   title: player.homeTheaterDisplayName,
								   subtitle: subtitle,
								   additionalText: nil)
					}
				}
				return nil
			}
			
			if anyUpdates {
				let row = Row(type: .updateAll,
							  title: NSLocalizedString("Update All Speaker Firmware", comment: "Update all TV row"),
							  subtitle: nil,
							  additionalText: nil)
				rows.append(row)
			}
			
			let section = Section(type: .speakers ,
								  title: NSLocalizedString("SPEAKERS", comment: "Speakers header title"),
								  rows: rows)
			newSections.append(section)
		}

		let resetRow = Row(type: .reset,
						   title: NSLocalizedString("Reset Jukebox", comment: "Reset row"),
						   subtitle: nil,
						   additionalText: nil)
		let section = Section(type: .general,
							  title: NSLocalizedString("GENERAL", comment: "General header title"),
							  rows: [resetRow])
		newSections.append(section)
		sections = newSections

		tableView.reloadData()
	}
}
 */
