package com.seven.ikar.kotlin.feature.call

import android.media.AudioManager
import android.media.ToneGenerator

class AndroidCallTonePlayer {
    private var toneGenerator: ToneGenerator? = null
    private var isOutgoingRingbackActive: Boolean = false

    fun startOutgoingRingback() {
        if (isOutgoingRingbackActive) {
            return
        }

        val generator = runCatching {
            ToneGenerator(AudioManager.STREAM_RING, OUTGOING_RINGBACK_VOLUME)
        }.getOrNull() ?: return

        stopOutgoingRingback()
        toneGenerator = generator
        isOutgoingRingbackActive = true

        val started = generator.startTone(
            ToneGenerator.TONE_CDMA_NETWORK_USA_RINGBACK,
            OUTGOING_RINGBACK_DURATION_MS
        )
        if (!started) {
            generator.startTone(
                ToneGenerator.TONE_SUP_RINGTONE,
                OUTGOING_RINGBACK_DURATION_MS
            )
        }
    }

    fun stopOutgoingRingback() {
        isOutgoingRingbackActive = false
        toneGenerator?.runCatching { stopTone() }
        toneGenerator?.release()
        toneGenerator = null
    }

    companion object {
        private const val OUTGOING_RINGBACK_VOLUME = 80
        private const val OUTGOING_RINGBACK_DURATION_MS = 120_000
    }
}
