package com.humand.demo.modules.Audio

import android.content.Context
import android.util.Log

/**
 * Coordinates audio routing between calls and livestreams.
 * With mutual exclusion, only one audio context can be active at a time.
 */
object AudioRouteCoordinator {
    private const val TAG = "AudioRouteCoordinator"

    @Volatile private var isCallActive: Boolean = false
    @Volatile private var callPrefersSpeaker: Boolean = false
    @Volatile private var isLivestreamActive: Boolean = false
    @Volatile private var livestreamWantsSpeaker: Boolean = false

    fun setCallRoute(context: Context, active: Boolean, prefersSpeaker: Boolean) {
        isCallActive = active
        callPrefersSpeaker = prefersSpeaker

        if (!active) {
            callPrefersSpeaker = false
            // Configure speaker for next audio context (if any)
            AudioSessionHelper.getInstance(context.applicationContext).configureForSpeaker()
        }
    }

    fun updateCallSpeakerPreference(prefersSpeaker: Boolean) {
        if (isCallActive) {
            callPrefersSpeaker = prefersSpeaker
        }
    }

    fun setLivestreamRoute(context: Context, active: Boolean, wantsSpeaker: Boolean) {
        isLivestreamActive = active
        livestreamWantsSpeaker = if (active) wantsSpeaker else false

        if (active && wantsSpeaker) {
            Log.d(TAG, "Configuring livestream speaker route")
            AudioSessionHelper.getInstance(context.applicationContext).configureForSpeaker()
        }
    }

    fun handleCallEnded(context: Context) {
        setCallRoute(context, active = false, prefersSpeaker = false)
    }
}
