//
//  PreVideoController.swift
//  PhoneManager
//
//  Created by 赵前 on 2025/4/6.
//

import Foundation

import AVFoundation
import Photos
class PreVideoController : BaseViewController {

    private var player: AVPlayer?
        private var playerLayer: AVPlayerLayer?
        private let localIdentifier: String

        init(localIdentifier: String) {
            self.localIdentifier = localIdentifier
            super.init(nibName: nil, bundle: nil)
        }

        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func viewDidLoad() {
            super.viewDidLoad()
            setupVideoPlayer()
            setupTapGesture()
        }

        private func setupVideoPlayer() {
            guard let asset = fetchAsset() else { return }

            let options = PHVideoRequestOptions()
            options.version = .current
            options.deliveryMode = .highQualityFormat
            options.isNetworkAccessAllowed = true
            
            PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { [weak self] (avAsset, _, _) in
                guard let self = self, let avAsset = avAsset as? AVURLAsset else { return }

                DispatchQueue.main.async {
                    self.player = AVPlayer(url: avAsset.url)
                    self.player?.volume = 0
                    self.player?.isMuted = true
                    self.playerLayer = AVPlayerLayer(player: self.player)
                    self.playerLayer?.frame = CGRect(x: 0, y: self.titleView.height, width: self.view.width, height: self.view.height - self.titleView.height)
                    self.view.layer.addSublayer(self.playerLayer!)
                    self.player?.play()
                }
            }
        }

        private func fetchAsset() -> PHAsset? {
            let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: nil)
            return fetchResult.firstObject
        }

        private func setupTapGesture() {
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
            view.addGestureRecognizer(tapGesture)
        }

        @objc private func handleTap() {
            if presentedViewController != nil {
                dismiss(animated: true, completion: nil)
            } else {
                navigationController?.popViewController(animated: true)
            }
        }

        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(animated)
            player?.pause()
        }
}
