//
//  MPVolumeManager.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/3/29.
//

import Foundation
import UIKit
import MediaPlayer
import AVFoundation
///音量控制器（获取修改系统音量）
class MPVolumeManager:NSObject {
    static let shared = MPVolumeManager()
    //系统音量控制View
    private var volumeView:MPVolumeView?
    //自定义渐变色Slider
    private var systemVolumeSlider: UISlider?
    private override init() {
        super.init()
        //为音频会话添加KVO监听
        AVAudioSession.sharedInstance().addObserver(self, forKeyPath: "outputVolume", options: [.old, .new], context: nil)
    }
    deinit {
        //移除所有监听
        AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: "outputVolume")
    }
    //重新持有系统volum控制器
    func createVolume() {
        volumeView = .init()
        // 添加音量视图到界面，但隐藏它
        volumeView!.frame = CGRect(x: -100, y: -100, width: 0, height: 0)
        UIApplication.shared.windows.first?.addSubview(volumeView!)
        // 查找系统音量滑块
        for view in volumeView!.subviews {
            if let slider = view as? UISlider {
                systemVolumeSlider = slider
                break
            }
        }
    }
    //销毁系统volum控制器
    func destroyVolume() {
        guard volumeView != nil else {
            return
        }
        volumeView!.removeFromSuperview()
        systemVolumeSlider = nil
        volumeView = nil
    }
    //设置系统音量
    func setVolume(_ volume: Float) {
        systemVolumeSlider?.setValue(volume, animated: false)
    }
    //获取系统音量
    func getVolume() -> Float {
        //获取AVAudioSession
        getSystemVolume()
    }
    //获取系统音量
    private func getSystemVolume() -> Float{
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(true)
            return audioSession.outputVolume
        } catch {
            print("Error getting system volume: \(error.localizedDescription)")
            return 0.0
        }
    }
    //KVO
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "outputVolume" {
            if let volume = change?[.newKey] as? Float {
                
                //将获得volume值通知传出
                NotificationCenter.notificationKey.post(notificationName: .volume_change, object: volume)
            }
        }
    }
}
