//
//  SecretVideoPlayer.swift
//  PhoneManager
//
//  Created by edy on 2025/4/3.
//

import UIKit
import AVFoundation


class SecretVideoPlayer: UIView {
    
    var callBackCurrtntTimeString : (String)->Void = {currentTimeString in }
    
    var tapPauseCallback : (playState)->Void = {state in}
    
    var timeObserverToken: Any?

    private var player: AVPlayer?
    var isLooping = false
    
    enum PlayerFrom {
    case home
    case other
    }
    
    enum playState {
        case start
        case playing
        case pause
        case end
    }
    
    var fromState:PlayerFrom = .other
    
    var state:playState = .start
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupPlayerLayer()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupPlayerLayer()
    }

    @objc func tapClick() -> Void {
        if state == .pause || state == .start {
            resume()
            state = .playing
        }else if state == .end {
            state = .playing
            player?.seek(to: CMTime.zero)
            resume()
        }else{
            state = .pause
            pause()
        }
        self.tapPauseCallback(state)
    }
    
    private func setupPlayerLayer() {
        backgroundColor = .clear
        let playerLayer = AVPlayerLayer()
        playerLayer.backgroundColor = UIColor.clear.cgColor
        playerLayer.shouldRasterize = true
        playerLayer.rasterizationScale = UIScreen.main.scale
        layer.addSublayer(playerLayer)
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapClick))
        self.addGestureRecognizer(tap)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let playerLayer = layer.sublayers?.first as? AVPlayerLayer {
            playerLayer.frame = bounds
            
        }
    }
    
    func playVideo(from url: URL?) {
        if url == nil {
            return
        }
        removeObservers()
        player = AVPlayer(url: url!)
        if let playerLayer = layer.sublayers?.first as? AVPlayerLayer {
            playerLayer.player = player
            player?.volume = 0
            player?.isMuted = true
            if fromState == .home {
                playerLayer.videoGravity = .resizeAspectFill
            }else{
                playerLayer.videoGravity = .resizeAspect
            }
        }
        NotificationCenter.default.addObserver(
            self,
            selector: #selector( playerItemDidReachEnd),
            name: .AVPlayerItemDidPlayToEndTime,
            object: player?.currentItem
        )
        addTimeObserver()
  
        state = .playing
        
        player?.play()
    }
    
    func addTimeObserver(){
        let interval = CMTime(seconds: 0.1, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
        
        timeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: .main) { [weak self] time in
            guard let self = self, let currentItem = self.player?.currentItem else { return }
            
            let currentTime = time.seconds
            _ = currentItem.duration.seconds
            
            // 更新进度标签
            self.callBackCurrtntTimeString("\(self.formatTime(seconds: currentTime))")
        }
    }
    
    // 播放完成回调
    @objc private func playerItemDidReachEnd(notification: Notification) {
        if isLooping {
            player?.seek(to: CMTime.zero)
            player?.play()
        }
        state = .end
        self.tapPauseCallback(state)
    }
    
    // 暂停播放
    func pause() {
        state = .pause
        player?.pause()
    }
    
    // 继续播放
    func resume() {
        state = .playing
        player?.play()
    }
    
    // 移除观察者
    private func removeObservers() {
        NotificationCenter.default.removeObserver(
            self,
            name: .AVPlayerItemDidPlayToEndTime,
            object: nil
        )
        
        if let token = timeObserverToken {
            self.player?.removeTimeObserver(token)
            timeObserverToken = nil
        }
    }
    
    // 清理资源
    deinit {
        removeObservers()
    }
    
    func formatTime(seconds: Double) -> String {
            guard !seconds.isNaN else { return "00:00" }
            
            let totalSeconds = Int(seconds)
            let hours = totalSeconds / 3600
            let minutes = (totalSeconds % 3600) / 60
            let seconds = totalSeconds % 60
            
            if hours > 0 {
                return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
            } else {
                return String(format: "%02d:%02d", minutes, seconds)
            }
        }
}
