package club.clubk.ktag.apps.konfigurator

import android.content.Context
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.util.Log

class SoundManager(private val context: Context) {
    private var soundPool: SoundPool? = null
    private var doubleChirpID: Int = 0
    private var isLoaded = false

    init {
        // Initialize the SoundPool
        soundPool = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder()
                .setMaxStreams(3)  // Allow up to 3 simultaneous sounds
                .setAudioAttributes(
                    AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build()
                )
                .build()
        } else {
            @Suppress("DEPRECATION")
            SoundPool(3, AudioManager.STREAM_MUSIC, 0)
        }

        // Set up load listener to know when sound is ready to play
        soundPool?.setOnLoadCompleteListener { _, _, status ->
            isLoaded = status == 0
            if (isLoaded) {
                playDoubleChirp()
            }
        }

        // Load the click sound (place your click.wav file in res/raw)
        doubleChirpID = soundPool?.load(context, R.raw.double_chirp, 1) ?: 0
    }

    fun playDoubleChirp() {
        if (isLoaded) {
            // Play the sound with:
            // leftVolume, rightVolume (1f = full volume)
            // priority (0 = lowest)
            // loop (0 = no loop)
            // rate (1f = normal playback speed)
            soundPool?.play(doubleChirpID, 1f, 1f, 0, 0, 1f)
        }
    }

    // Important: Release resources when no longer needed
    fun release() {
        soundPool?.release()
        soundPool = null
    }
}
