//
//  PlayContoller4.swift
//  tdvideo
//
//  Created by mac on 2024/2/1.
//


import AVKit
import UIKit

//class PlayContoller4: UIViewController {
//    
//    private var playerViewController: AVPlayerViewController?
//    private var player: AVPlayer?
//    
//    var link = false
//    var play = false
//    var btn:UIButton?
//    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        view.backgroundColor = UIColor.brown
//        
//        
//        
//        btn = UIButton(type: UIButton.ButtonType.custom)
//        self.view.addSubview(btn!)
//        btn!.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
//        btn!.setTitle("未连接", for: UIControl.State.normal)
//        btn!.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControl.Event.touchUpInside)
//        
//        // 创建 AVPlayerViewController
//        playerViewController = AVPlayerViewController()
//        playerViewController?.view.frame = CGRect(x: 0, y: 200, width: self.view.frame.size.width, height: 350)
//        addChild(playerViewController!)
//        view.addSubview(playerViewController!.view)
//        
//        // 创建 AVPlayer
//        guard let videoURL = Bundle.main.url(forResource: "IMG_0071", withExtension: "MOV") else {
//            print("无法加载视频文件")
//            return
//        }
//        player = AVPlayer(url: videoURL)
//        playerViewController?.player = player
//        player?.play()
//        
//        // 监听 UIScreenMirroringDidChange 通知
//        NotificationCenter.default.addObserver(self, selector: #selector(screenMirroringChanged(_:)), name: UIScreen.didConnectNotification, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(screenMirroringChanged(_:)), name: UIScreen.didDisconnectNotification, object: nil)
//        
//        
//        // 监听 AirPlay 设备的连接状态
////        NotificationCenter.default.addObserver(self, selector: #selector(airPlayStatusDidChange(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
//        
//        // 获取当前投屏状态
//        let isScreenMirroring = UIScreen.screens.count > 1
//        print("Screen Mirroring: \(isScreenMirroring)")
//        setttinisScreenMirroring(isScreenMirroring: isScreenMirroring)
//    }
//    
//    @objc private func screenMirroringChanged(_ notification: NSNotification) {
//        // 投屏状态发生变化
//        let isScreenMirroring = UIScreen.screens.count > 1
//        print("Screen Mirroring: \(isScreenMirroring)")
//        setttinisScreenMirroring(isScreenMirroring: isScreenMirroring)
//    }
//    
//    func setttinisScreenMirroring(isScreenMirroring:Bool){
//        
//        //已连接
//        if(isScreenMirroring){
//            link = true
////            let currentRoute = AVAudioSession.sharedInstance().currentRoute
////            let isAirPlayActive = currentRoute.outputs.contains { output in
////                return output.portType == AVAudioSession.Port.airPlay
////            }
//            if(play == true){
//                player!.usesExternalPlaybackWhileExternalScreenIsActive = true
//                player!.allowsExternalPlayback = true
//                btn!.setTitle("串流中", for: UIControl.State.normal)
//            }else{
//                player!.usesExternalPlaybackWhileExternalScreenIsActive = false
//                player!.allowsExternalPlayback = false
//                btn!.setTitle("已连接", for: UIControl.State.normal)
//            }
//        }
//        
//        //未连接
//        else{
//            link = false
//            // 当前未连接到 AirPlay 设备
//            player!.usesExternalPlaybackWhileExternalScreenIsActive = false
//            player!.allowsExternalPlayback = false
//            btn!.setTitle("未连接", for: UIControl.State.normal)
//        }
//    }
//    
//    @objc private func airPlayStatusDidChange(_ notification: Notification) {
//        print("设备连接发生变化")
//    }
//    
//    deinit {
//        NotificationCenter.default.removeObserver(self)
//    }
//    
//    @objc func buttonPressed(sender:UIButton){
//        
//        if(link == true){
//            play = !play
//            if(play == true){
//                // 当前已连接到 AirPlay 设备
//                player!.usesExternalPlaybackWhileExternalScreenIsActive = true
//                player!.allowsExternalPlayback = true
//                btn!.setTitle("在串流", for: UIControl.State.normal)
//            }else{
//                player!.usesExternalPlaybackWhileExternalScreenIsActive = false
//                player!.allowsExternalPlayback = false
//                btn!.setTitle("已连接", for: UIControl.State.normal)
//            }
//        }
//    }
//}



class PlayContoller4: UIViewController {
    private var playerViewController: AVPlayerViewController?
    private var player: AVPlayer?
    
    var link = false
    var play = false
    var btn:UIButton?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.brown
        
        btn = UIButton(type: UIButton.ButtonType.custom)
        self.view.addSubview(btn!)
        btn!.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
        btn!.setTitle("未连接设备", for: UIControl.State.normal)
        btn!.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControl.Event.touchUpInside)
        btn!.layer.borderWidth = 1
        btn!.layer.borderColor = UIColor.white.cgColor
        
        // 创建 AVPlayerViewController
        playerViewController = AVPlayerViewController()
        playerViewController?.view.frame = CGRect(x: 0, y: 200, width: self.view.frame.size.width, height: 350)
        addChild(playerViewController!)
        view.addSubview(playerViewController!.view)
        
        // 创建 AVPlayer
        guard let videoURL = Bundle.main.url(forResource: "IMG_0071", withExtension: "MOV") else {
            print("无法加载视频文件")
            return
        }
        player = AVPlayer(url: videoURL)
        playerViewController?.player = player
        
        // 监听 AirPlay 设备的连接状态
        NotificationCenter.default.addObserver(self, selector: #selector(airPlayStatusDidChange(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 检查当前是否已连接到 AirPlay 设备
        checkAirPlayStatus()
    }
    
    @objc private func airPlayStatusDidChange(_ notification: Notification) {
        checkAirPlayStatus()
    }
    
    private func checkAirPlayStatus() {
        print("设备连接变化")
        let currentRoute = AVAudioSession.sharedInstance().currentRoute
        let isAirPlayActive = currentRoute.outputs.contains { output in
            return output.portType == AVAudioSession.Port.HDMI ||
            output.portType == AVAudioSession.Port.airPlay
        }
        
        setttinisScreenMirroring(isScreenMirroring: isAirPlayActive)
    }
    
    func setttinisScreenMirroring(isScreenMirroring:Bool){

        //已连接
        if(isScreenMirroring){
            print("已连接")
            link = true
            play = true
            player!.usesExternalPlaybackWhileExternalScreenIsActive = true
            player!.allowsExternalPlayback = true
            btn!.setTitle("串流播放中", for: UIControl.State.normal)
            player!.play()
        }

        //未连接
        else{
            print("未连接")
            link = false
            play = false
            // 当前未连接到 AirPlay 设备
            player!.usesExternalPlaybackWhileExternalScreenIsActive = false
            player!.allowsExternalPlayback = false
            btn!.setTitle("未连接设备", for: UIControl.State.normal)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func buttonPressed(sender:UIButton){
        
        if(link == true){
            play = !play
            if(play == true){
                // 当前已连接到 AirPlay 设备
                player!.usesExternalPlaybackWhileExternalScreenIsActive = true
                player!.allowsExternalPlayback = true
                btn!.setTitle("串流播放中", for: UIControl.State.normal)
            }else{
                player!.usesExternalPlaybackWhileExternalScreenIsActive = false
                player!.allowsExternalPlayback = false
                btn!.setTitle("已连接设备", for: UIControl.State.normal)
            }
        }
    }
}





//import UIKit
//import ExternalAccessory
//
//class PlayContoller4: UIViewController {
//
//    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        self.view.backgroundColor = UIColor.brown
//        
//        
//        NotificationCenter.default.addObserver(self, selector: #selector(didConnectAccessory(_:)), name: Notification.Name.EAAccessoryDidConnect, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(didDisconnectAccessory(_:)), name: Notification.Name.EAAccessoryDidDisconnect, object: nil)
//        EAAccessoryManager.shared().registerForLocalNotifications()
//        print(EAAccessoryManager.shared().connectedAccessories)
//    }
//        
//        
//        @objc
//    private func didConnectAccessory(_ notification: NSNotification) {
//        let accessoryManager = EAAccessoryManager.shared()
//        for accessory in accessoryManager.connectedAccessories {
//            print(accessory.protocolStrings)
//            if accessory.protocolStrings.contains("") {
//                //We have found the accessory corresponding to our gadget
//                let description = """
//                Accessory name: \(accessory.name)
//                Manufacturer: \(accessory.manufacturer)
//                Model number: \(accessory.modelNumber)
//                Serial number: \(accessory.serialNumber)
//                HW Revision: \(accessory.hardwareRevision)
//                FW Revision: \(accessory.firmwareRevision)
//                Connected: \(accessory.isConnected)
//                Connection ID: \(accessory.connectionID)
//                Protocol strings: \(accessory.protocolStrings.joined(separator: "; "))
//                """
//                print(description)
//              
//            }
//            
////            self.accessory = accessory
//            
//        }
//    }
//        
//    @objc
//    private func didDisconnectAccessory(_ notification: NSNotification) {
//        print("disconnect")
//    }
//}
