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

import Foundation
import AVFoundation

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

    fileprivate var _timerID: TimerID
    
    init(timerID: TimerID, soundFile: SoundFile) throws {
        self._timerID = timerID
        
        guard let url = soundFile.url else {
            throw SoundPlayerError.missingResourceError(file: soundFile)
        }
        
        self._player = try AVAudioPlayer(contentsOf: url)
    }
    
    func restore(for playDate: Date, repeatCount: Int) throws {
        let timeLeft = playDate.timeIntervalSinceNow
        try self._play(in: timeLeft, repeatCount: repeatCount)
    }
    
    func start(in duration: TimeInterval, repeatCount: Int) throws {
        try self._play(in: duration, repeatCount: repeatCount)
    }
    
    fileprivate func _play(in duration: TimeInterval, repeatCount: Int) throws {
        
        let audioSession: AVAudioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(.playback, options: .duckOthers)
        try audioSession.setActive(true)

        self._player.prepareToPlay()
        self._player.volume = 1.0
        self._player.delegate = self
        self._player.numberOfLoops = repeatCount
        
        self._player.play(atTime: self._player.deviceCurrentTime + duration)

    }
    
    func stop() {
        self._player.stop()
    }
    
    // MARK: - Delegate

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        Logger.log("audioPlayerDidFinishPlaying: successfully = \(flag)")
        Conductor.maestro.cancelSoundPlayer(id: self._timerID)
    }
    
}
