//
//  VideoViewController.swift
//  PhoneManager
//
//  Created by edy on 2025/5/13.
//

import Foundation
import AVKit
import MediaPlayer

class VideoViewController: UIViewController {
    
    var url : URL?
    
    var isAutoPlay : Bool = true
    
    // 系统播放器控制器
    let playerViewController = AVPlayerViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupPlayer()
    }
    
    var player:AVPlayer?
    
    func setupPlayer() {
        // 1. 创建播放器
        if let url = self.url {
            self.player = AVPlayer(url: url)
            self.player?.automaticallyWaitsToMinimizeStalling = false
            
            self.player?.volume = 0
            self.player?.isMuted = true
            // 2. 配置播放器控制器
            self.playerViewController.videoGravity = .resizeAspect
            self.playerViewController.player = self.player
            self.playerViewController.delegate = self
            self.playerViewController.showsPlaybackControls = true
            // 3. 添加到当前视图
            self.addChild(self.playerViewController)
            self.view.addSubview(self.playerViewController.view)
            self.playerViewController.view.frame = self.view.bounds
            self.playerViewController.didMove(toParent: self)
            // 4. 自动播放
            if self.isAutoPlay {
                self.player?.play()
            }
        }
    }
}

// MARK: - AVPlayerViewControllerDelegate
extension VideoViewController: AVPlayerViewControllerDelegate {
    // 处理全屏切换
    func playerViewController(_ playerViewController: AVPlayerViewController,
                             willBeginFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    }
    
    func playerViewController(_ playerViewController: AVPlayerViewController,
                             willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    }
}
