//
//  VolumeButtonObserver.swift
//  SelfieCam
//
//  Observes hardware volume button presses and triggers a callback.
//  Used to enable shutter capture via volume buttons.
//

import AVFoundation
import Combine
import MediaPlayer
import SwiftUI

/// Observes volume button presses and calls the provided action.
/// Hides the system volume HUD while observing.
@MainActor
final class VolumeButtonObserver: ObservableObject {
    @Published private(set) var isObserving = false
    
    private var volumeObservation: NSKeyValueObservation?
    private var onVolumeButtonPress: (@MainActor () -> Void)?
    private var lastVolume: Float = 0.5
    
    /// Starts observing volume button presses
    /// - Parameter action: Closure called when volume button is pressed
    func startObserving(action: @escaping @MainActor () -> Void) {
        guard !isObserving else { return }
        
        self.onVolumeButtonPress = action
        self.isObserving = true
        
        let audioSession = AVAudioSession.sharedInstance()
        
        do {
            try audioSession.setActive(true)
            lastVolume = audioSession.outputVolume
        } catch {
            print("Failed to activate audio session: \(error)")
            return
        }
        
        // Observe volume changes using KVO
        volumeObservation = audioSession.observe(\.outputVolume, options: [.new, .old]) { [weak self] _, change in
            guard let newVolume = change.newValue,
                  let oldVolume = change.oldValue,
                  newVolume != oldVolume else { return }
            
            // Trigger capture on volume button press (either up or down)
            Task { @MainActor [weak self] in
                self?.onVolumeButtonPress?()
            }
        }
    }
    
    /// Stops observing volume button presses
    func stopObserving() {
        volumeObservation?.invalidate()
        volumeObservation = nil
        onVolumeButtonPress = nil
        isObserving = false
        
        try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
    }
}

// MARK: - Hidden Volume View

/// A hidden MPVolumeView that prevents the system volume HUD from appearing
struct HiddenVolumeView: UIViewRepresentable {
    func makeUIView(context: Context) -> MPVolumeView {
        let volumeView = MPVolumeView(frame: .zero)
        volumeView.alpha = 0.0001 // Nearly invisible but still functional
        volumeView.isUserInteractionEnabled = false
        return volumeView
    }
    
    func updateUIView(_ uiView: MPVolumeView, context: Context) {}
}
