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

import UIKit

class AdjustAudioIntroViewController: UIViewController {
	// MARK: Public Properties
	var soundbarPlayerID: String?
    var soundbarDeviceID: String?
	
	// MARK: Private Properties/Types
	private struct Segues {
		static let showVolumes = "showVolumes"
	}
	private var bailOutViewController: UIViewController?
}

extension AdjustAudioIntroViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareModalNavigationBar()
    }
    
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		let vcs = navigationController?.viewControllers ?? []
		if vcs.count > 1 {
			bailOutViewController = vcs[vcs.count - 2]
		} else {
			bailOutViewController = navigationController?.topViewController
		}
		
		// No title for back button to centre next title
		let bbi = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
		navigationItem.backBarButtonItem = bbi
	}
	
	override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
		if let volumesVC = segue.destination as? AdjustAudioVolumesViewController {
			volumesVC.injectDependencies(preferences: preferences, playerController: playerController)
			volumesVC.soundbarPlayerID = soundbarPlayerID
            volumesVC.soundbarDeviceID = soundbarDeviceID
			volumesVC.bailOutViewController = bailOutViewController
		}
	}
}


extension AdjustAudioIntroViewController {
	@IBAction private func nextTapped(_ sender: Any?) {
		let missingChannels = missingChannelsForSoundbar()
		if missingChannels.count == 0 {
			performSegue(withIdentifier: Segues.showVolumes, sender: self)
			return
		} else {
			let textAttrs: [NSAttributedString.Key : Any] = [.font : UIFont.systemFont(ofSize: 14, weight: .light) as Any,
                                                             .foregroundColor: ColorCompat.label]
			let text = NSAttributedString(string: NSLocalizedString("The following speakers cannot be found on the network: ", comment: "Alert"),
										  attributes: textAttrs)
			
			let boldAttrs: [NSAttributedString.Key : Any] = [.font : UIFont.systemFont(ofSize: 14, weight: .bold) as Any,
															.foregroundColor: ColorCompat.label]
			let speakers = missingChannels.joined(separator: ", ") + ".\n\n"
			let boldText = NSAttributedString(string: speakers, attributes: boldAttrs)
			
			let qtext = NSAttributedString(string: NSLocalizedString("Do you want to continue?", comment: "Alert"),
										   attributes: textAttrs)
			
			let str = NSMutableAttributedString()
			str.append(text)
			str.append(boldText)
			str.append(qtext)
			
			let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
			alert.setValue(str, forKey: "attributedMessage")
			alert.addAction(UIAlertAction(title: NSLocalizedString("EXIT SETUP", comment: "Alert"),
										  style: .cancel,
										  handler: { _ in
											self.navigationController?.popToViewController(self.bailOutViewController!,
																						   animated: true)
			}))
			
			alert.addAction(UIAlertAction(title: NSLocalizedString("CONTINUE", comment: "Alert"),
										  style: .default,
										  handler: { _ in
											self.performSegue(withIdentifier: Segues.showVolumes, sender: self)
			}))
			
			present(alert, animated: true, completion: nil)
		}
	}
}

extension AdjustAudioIntroViewController {
	private func missingChannelsForSoundbar() -> [String] {
		var missingChannels: [String] = []
		if let soundbar = playerController.player(id: soundbarPlayerID!) {
			if soundbar.haveHomeTheaterChannel(.subwoofer) &&
				!soundbar.isHomeTheaterChannelAvailable(.subwoofer) {
				missingChannels.append(NSLocalizedString("Subwoofer", comment: "Home Theater"))
			}
			
			if soundbar.haveHomeTheaterChannel(.leftSurround) &&
				!soundbar.isHomeTheaterChannelAvailable(.leftSurround) {
				missingChannels.append(NSLocalizedString("Left Surround", comment: "Home Theater"))
			}
			
			if soundbar.haveHomeTheaterChannel(.rightSurround) &&
				!soundbar.isHomeTheaterChannelAvailable(.rightSurround) {
				missingChannels.append(NSLocalizedString("Right Surround", comment: "Home Theater"))
			}

            if soundbar.haveHomeTheaterChannel(.leftRearSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.leftRearSurround) {
                missingChannels.append(NSLocalizedString("Left Rear Surround", comment: "Home Theater"))
            }

            if soundbar.haveHomeTheaterChannel(.rightRearSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.rightRearSurround) {
                missingChannels.append(NSLocalizedString("Right Rear Surround", comment: "Home Theater"))
            }

            if soundbar.haveHomeTheaterChannel(.leftUpfiringSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.leftUpfiringSurround) {
                missingChannels.append(NSLocalizedString("Left Upfiring Surround", comment: "Home Theater"))
            }

            if soundbar.haveHomeTheaterChannel(.rightUpfiringSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.rightUpfiringSurround) {
                missingChannels.append(NSLocalizedString("Right Upfiring Surround", comment: "Home Theater"))
            }

            if soundbar.haveHomeTheaterChannel(.leftRearUpfiringSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.leftRearUpfiringSurround) {
                missingChannels.append(NSLocalizedString("Left Rear Upfiring Surround", comment: "Home Theater"))
            }

            if soundbar.haveHomeTheaterChannel(.rightRearUpfiringSurround) &&
                !soundbar.isHomeTheaterChannelAvailable(.rightRearUpfiringSurround) {
                missingChannels.append(NSLocalizedString("Right Rear UpfiringSurround", comment: "Home Theater"))
            }

		}
		return missingChannels
	}
	
}
