//
//  AudioEngine.swift
//  Werkout_ios
//
//  Created by Trey Tartt on 6/21/24.
//

import AVKit
import AVFoundation

class AudioEngine {
    static let shared = AudioEngine()
    private init() { }
    
    var audioPlayer: AVAudioPlayer?
    var avPlayer: AVPlayer?
    
    func playRemoteAudio(fromURL url: URL) {
#if os(iOS)
        let playerItem = AVPlayerItem(url: url)
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback,
                                                            mode: .default,
                                                            options: [.mixWithOthers])
            try AVAudioSession.sharedInstance().setActive(true)
            
            avPlayer = AVPlayer(playerItem: playerItem)
            avPlayer?.play()
        } catch {
            print("ERROR")
        }
#endif
    }
    
    func playBeep() {
#if os(iOS)
        if let path = Bundle.main.path(forResource: "short_beep", ofType: "m4a") {
            do {
                try AVAudioSession.sharedInstance().setCategory(.playback,
                                                                mode: .default,
                                                                options: [.mixWithOthers])
                try AVAudioSession.sharedInstance().setActive(true)
                
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                audioPlayer?.play()
            } catch {
                print("ERROR")
            }
        }
#endif
    }
    
    func playFinished() {
#if os(iOS)
        if let path = Bundle.main.path(forResource: "long_beep", ofType: "m4a") {
            do {
                try AVAudioSession.sharedInstance().setCategory(.playback,
                                                                mode: .default,
                                                                options: [.mixWithOthers])
                try AVAudioSession.sharedInstance().setActive(true)
                
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                audioPlayer?.play()
            } catch {
                print("ERROR")
            }
        }
#endif
    }
}
