//
//  BackgroundSoundPlayer.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 08/03/2023.
//

import Foundation
import AVFoundation

@objc class DelaySoundPlayer: NSObject, AVAudioPlayerDelegate {
    
    fileprivate var _player: AVAudioPlayer?

    private var soundFile: SoundFile
    
    init(soundFile: SoundFile) {
        self.soundFile = soundFile
    }
    
    func start(in duration: TimeInterval, repeatCount: Int) throws {
        
        guard let url = self.soundFile.url else {
            throw SoundPlayerError.missingResourceError(file: self.soundFile)
        }

        let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(.playback, options: .duckOthers)
        try audioSession.setActive(true)

        let player = try AVAudioPlayer(contentsOf: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.delegate = self
        player.numberOfLoops = repeatCount
        
        self._player = player

        player.play(atTime: player.deviceCurrentTime + duration)
    }
    
    func stop() {
        self._player?.stop()
    }
    
    // MARK: - Delegate
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        
        let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
        do {
            self.stop()
            try audioSession.setActive(false)
        } catch {
            Logger.error(error)
        }
        
        Logger.log("audioPlayerDidFinishPlaying: successfully = \(flag)")
    }
    
}
