package audio

import audio.Bass.BASS_ACTIVE_PLAYING
import audio.Bass.BASS_DEVICE_ENABLED
import audio.Bass.BASS_DEVICE_INIT
import audio.Bass.BASS_POS_BYTE
import audio.Bass.BASS_STREAM_DECODE
import audio.Bass.BASS_SAMPLE_MONO
import audio.Bass.STREAMPROC_PUSH
import audio.BassEnc.BASS_ENCODE_PCM
import codes.Somecodes.Companion.ValidFile
import codes.Somecodes.Companion.ValidString
import com.sun.jna.Memory
import org.tinylog.Logger
import java.util.function.BiConsumer

@Suppress("unused")
class AudioPlayer (var samplingrate: Int) {
    val bass: Bass = Bass.Instance
    val bassenc : BassEnc = BassEnc.Instance
    var initedDevice = -1




    init {
        if (samplingrate<1) samplingrate = 44100 // Default sampling rate
        Logger.info {"Bass version ${Integer.toHexString(bass.BASS_GetVersion())}"}
        Logger.info { "BassEnc version ${Integer.toHexString(bassenc.BASS_Encode_GetVersion())}" }
        InitAudio(0)    // Audio 0 is No Sound, use for reading and writing wav silently
    }

    /**
     * Initializes the audio system with the specified device ID.
     * Call it before using any audio functions.
     * @param id The device ID to initialize.
     * @return True if initialization was successful, false otherwise.
     */
    fun InitAudio(id : Int) : Boolean {

        val bdi = Bass.BASS_DEVICEINFO()
        if (bass.BASS_GetDeviceInfo(id, bdi)){
            Logger.info { "Audio ID=$id Name=${bdi.name} Driver=${bdi.driver}" }
            if (bdi.flags and BASS_DEVICE_ENABLED == 0) {
                Logger.error { "Audio ID=$id is not enabled, cannot initialize" }
                return false
            }
            if (bdi.flags and BASS_DEVICE_INIT > 0){
                Logger.info { "Audio ID=$id is already initialized" }
                if (id > 0) {
                    initedDevice = id
                    Logger.info { "Real Audio Device reused ID=$initedDevice" }
                }
                return true
            }
        }

        if (bass.BASS_Init(id, 48000, 0)){
            Logger.info { "Audio ID=$id inited succesfully" }
            if (id > 0) {
                initedDevice = id
                Logger.info { "Real Audio Device used ID=$initedDevice" }
            }
            return true
        } else {
            Logger.error { "Audio ID=$id initialization failed: ${bass.BASS_ErrorGetCode()}" }
            return false
        }
    }

    /**
     * Uninitializes the audio system if it was previously initialized.
     */
    fun UnInitAudio(){
        if (initedDevice != -1) {
            bass.BASS_SetDevice(initedDevice)
            if (bass.BASS_Free()) {
                Logger.info {"Audio ID=$initedDevice uninitialized successfully"}
            } else {
                Logger.error { "Audio ID=$initedDevice uninitialization failed: ${bass.BASS_ErrorGetCode()}"  }
            }
            initedDevice = -1
        }
    }

    /**
     * Loads an audio file and retrieves its information.
     * Check for isValid() method in AudioFileInfo class to verify the loaded file.
     * @param fileName The name of the audio file to load.
     * @return An AudioFileInfo object containing the file information.
     */
    fun LoadAudioFile(fileName: String) : AudioFileInfo {
        val result = AudioFileInfo()
        if (ValidFile(fileName)){
            result.fileName = fileName
            bass.BASS_SetDevice(0) // Set to No Sound device for reading
            val handle = bass.BASS_StreamCreateFile(false, fileName, 0L, 0L, BASS_STREAM_DECODE or BASS_SAMPLE_MONO)
            if (handle!=0){
                // successfully opened the file
                // read file size
                val size = bass.BASS_ChannelGetLength(handle, BASS_POS_BYTE)
                if (size > 0) {
                    result.fileSize = size
                }
                // read file duration
                val duration = bass.BASS_ChannelBytes2Seconds(handle, size)
                if (duration > 0) {
                    result.duration = duration
                }
                // read file bytes
                val mem = Memory(size)
                val bytesRead = bass.BASS_ChannelGetData(handle, mem, size.toInt())
                if (bytesRead > 0) {
                    result.bytes = mem.getByteArray(0, bytesRead)
                }

                // close the handle
                bass.BASS_StreamFree(handle)

            }
        }
        return result
    }

    /**
     * Writes the audio data from the sources to a WAV file.
     * @param sources List of AudioFileInfo objects containing the audio data to write.
     * @param target The target file name for the WAV file.
     * @param callback A BiConsumer that accepts a Boolean indicating success or failure and a String message.
     */
    fun WavWriter(sources: List<AudioFileInfo>, target: String, callback: BiConsumer<Boolean, String>) {
        if (sources.isEmpty() || !ValidFile(target)) {
            callback.accept(false, " Invalid sources")
            return
        }
        if (!ValidString(target)) {
            callback.accept(false, " Invalid target file name")
            return
        }

        val thread = Thread {
            bass.BASS_SetDevice(0) // Set to No Sound device for writing
            val streamhandle = bass.BASS_StreamCreate(samplingrate, 1, BASS_STREAM_DECODE, STREAMPROC_PUSH, null)
            if (streamhandle==0){
                callback.accept(false, "Failed to create stream: ${bass.BASS_ErrorGetCode()}")
                return@Thread
            }
            val encodehandle = bassenc.BASS_Encode_Start(streamhandle, target, BASS_ENCODE_PCM, null, null)
            if (encodehandle==0){
                bass.BASS_StreamFree(streamhandle)
                callback.accept(false, "Failed to start encoding: ${bass.BASS_ErrorGetCode()}")
                return@Thread
            }
            val playresult = bass.BASS_ChannelPlay(streamhandle,false)
            if (!playresult) {
                bassenc.BASS_Encode_Stop(encodehandle)
                bass.BASS_StreamFree(streamhandle)
                callback.accept(false, "BASS_ChannelPlay failed: ${bass.BASS_ErrorGetCode()}")
                return@Thread
            }

            var allsuccess = true
            sources.forEach { source ->
                if (source.isValid()) {
                    // write the bytes to the stream
                    val mem = Memory(source.bytes.size.toLong())
                    mem.write(0, source.bytes, 0, source.bytes.size)
                    val pushresult = bass.BASS_StreamPutData(streamhandle, mem, source.bytes.size)
                    if (pushresult == -1) {
                        Logger.error { "Failed to write data from ${source.fileName} to stream: ${bass.BASS_ErrorGetCode()}" }
                        allsuccess = false
                    }
                }
            }

            // now we wait until the stream is finished
            while(bassenc.BASS_Encode_IsActive(encodehandle) == BASS_ACTIVE_PLAYING) {
                Thread.sleep(100) // Sleep for a short time to avoid busy waiting
            }

            // close the encoding handle
            bassenc.BASS_Encode_Stop(encodehandle)
            bass.BASS_ChannelFree(streamhandle)
            if (allsuccess){
                callback.accept(true, "WAV file written successfully: $target")
            } else {
                callback.accept(false, "Failed to write some data to WAV file: $target")
            }
        }
        thread.name = "WavWriter Thread"
        thread.isDaemon = true
        thread.start()


    }


}