package audio

import java.util.function.Consumer

/**
 * Audio Player for playing audio files.
 * Supported extensions : .wav, .mp3
 */
@Suppress("unused")
class AudioFilePlayer(deviceID: Int, val filename: String, device_samplingrate: Int = 48000) {
    val bass: Bass = Bass.Instance
    var filehandle = 0
    init{
        if (bass.BASS_SetDevice(deviceID)){
            filehandle = bass.BASS_StreamCreateFile(false, filename, 0, 0, 0)
            if (filehandle == 0) {
                throw Exception("Failed to create stream for file $filename: ${bass.BASS_ErrorGetCode()}")
            }
        } else throw Exception("Failed to set device $deviceID")
    }

    fun Play(finished: Consumer<Any> ) : Boolean{
        if (bass.BASS_ChannelPlay(filehandle, false)){

            val thread = Thread{
                while(true){
                    Thread.sleep(1000)
                    if (bass.BASS_ChannelIsActive(filehandle)!= Bass.BASS_ACTIVE_PLAYING){
                        // finished playing
                        break
                    }
                }
                finished.accept(true)
            }
            thread.name = "AudioFilePlayer $filename"
            thread.isDaemon = true
            thread.start()
            return true
        }
        return false
    }
}