//
//  YHBasePlayerViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import AgoraRtcKit
import AVKit
import UIKit

class YHBasePlayerViewController: YHBaseViewController {
    // MARK: - Properties
    weak var player: YHPlayer?
    var playbackInfo: YHPlayerManager.PlaybackInfo?
    
    // 播放器设置
    var currentPlayingURL: String?
    var currentVideoTitle: String?
    
    // MARK: - UI Components
    lazy var containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        return view
    }()
    
    lazy var playerView: UIView = {
        let view = UIView()
        view.backgroundColor = .black
        return view
    }()
    
    lazy var topBarView: YHPlayerTopBarView = {
        let view = YHPlayerTopBarView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: k_Height_NavigationtBarAndStatuBar))
        return view
    }()
    
    // 控制状态
    private var isControlsVisible = true
    private var controlsAutoHideTimer: Timer?
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //setupGestures()
        //setupNotifications()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .black
        UIApplication.shared.isIdleTimerDisabled = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        gk_navBarAlpha = 1
        gk_navigationBar.isHidden = false
        view.backgroundColor = .black
//        controlsAutoHideTimer?.invalidate()
//        controlsAutoHideTimer = nil
        UIApplication.shared.isIdleTimerDisabled = false
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - Setup
    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = .black
        view.addSubview(containerView)
        containerView.addSubview(playerView)
        containerView.addSubview(topBarView)
        setupConstraints()
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        playerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        topBarView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
    }
    
//    private func setupGestures() {
//        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
//        containerView.addGestureRecognizer(tap)
//    }
//    
//    // MARK: - Controls Visibility
//    @objc private func handleTap() {
//        toggleControls()
//    }
//    
//    private func toggleControls() {
//        isControlsVisible.toggle()
//        //controlView.showControls(isControlsVisible)
//        resetControlsAutoHideTimer()
//    }
//    
//    private func resetControlsAutoHideTimer() {
//        controlsAutoHideTimer?.invalidate()
//        if isControlsVisible {
//            controlsAutoHideTimer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { [weak self] _ in
//                self?.hideControls()
//            }
//        }
//    }
//    
//    private func hideControls() {
//        isControlsVisible = false
//        //controlView.showControls(false)
//    }
}


// MARK: - Notifications
extension YHBasePlayerViewController {
    private func setupNotifications() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleAppDidEnterBackground),
            name: UIApplication.didEnterBackgroundNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleAppWillEnterForeground),
            name: UIApplication.willEnterForegroundNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(handleAudioSessionInterruption),
            name: AVAudioSession.interruptionNotification,
            object: nil
        )
    }
    
    @objc private func handleAppDidEnterBackground() {
        YHPlayerManager.shared.pause()
    }
    
    @objc private func handleAppWillEnterForeground() {
        YHPlayerManager.shared.resume()
    }
    
    @objc private func handleAudioSessionInterruption(_ notification: Notification) {
        guard let userInfo = notification.userInfo,
              let typeValue = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
              let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
            return
        }
        
        switch type {
        case .began:
            YHPlayerManager.shared.pause()
        case .ended:
            if let optionsValue = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
                let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
                if options.contains(.shouldResume) {
                    YHPlayerManager.shared.resume()
                }
            }
        @unknown default:
            break
        }
    }
}

// MARK: - Helper Methods
extension YHBasePlayerViewController {
    func formatTime(_ timeInMilliseconds: Int) -> String {
        let totalSeconds = timeInMilliseconds / 1000
        let minutes = totalSeconds / 60
        let seconds = totalSeconds % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
    
    func showAlert(message: String) {
        let alert = UIAlertController(title: "提示",
                                    message: message,
                                    preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - Orientation Support
extension YHBasePlayerViewController {
    override var shouldAutorotate: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .allButUpsideDown
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
}
