package com.useasy.callsdk.demo

import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothProfile
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.AudioManager
import com.useasy.callsdk.utils.AudioUtils
import com.useasy.callsdk.utils.Loger

/**
 * 音频路由变化监听器
 */
interface AudioRouteChangeListener {
    /**
     * 音频路由变化
     * @param route 音频路由类型：SPEAKER（外放）、RECEIVER（听筒）、BLUETOOTH（蓝牙）
     */
    fun onAudioRouteChanged(route: AudioRoute)
}

/**
 * 音频路由类型
 */
enum class AudioRoute {
    SPEAKER,    // 外放
    RECEIVER,   // 听筒
    BLUETOOTH   // 蓝牙
}

/**
 * 耳机插拔和蓝牙连接状态监听器
 */
class HeadsetPlugReceiver(
    private val context: Context,
    private val routeChangeListener: AudioRouteChangeListener? = null
) : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action ?: return
        Loger.dTag(TAG, "onReceive action: $action")

        when (action) {
            Intent.ACTION_HEADSET_PLUG -> {
                val state = intent.getIntExtra("state", 0)
                if (state == 0) {
                    // 耳机拔出
                    Loger.dTag(TAG, "耳机拔出，切换到外放")
                    AudioUtils.changeToSpeaker(context)
                    routeChangeListener?.onAudioRouteChanged(AudioRoute.SPEAKER)
                } else if (state == 1) {
                    // 耳机插入
                    Loger.dTag(TAG, "耳机插入，切换到听筒")
                    AudioUtils.changeToReceiver(context)
                    routeChangeListener?.onAudioRouteChanged(AudioRoute.RECEIVER)
                }
            }

            BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED -> {
                val state = intent.getIntExtra(
                    BluetoothHeadset.EXTRA_STATE,
                    BluetoothHeadset.STATE_DISCONNECTED
                )
                val previousState = intent.getIntExtra(
                    BluetoothHeadset.EXTRA_PREVIOUS_STATE,
                    BluetoothHeadset.STATE_DISCONNECTED
                )
                Loger.dTag(TAG, "蓝牙连接状态变化: previousState=$previousState, state=$state")
                updateBluetoothIndication(state)
            }

            AudioManager.ACTION_AUDIO_BECOMING_NOISY -> {
                // 音频输出变得嘈杂（例如耳机拔出），切换到外放
                Loger.dTag(TAG, "音频输出变得嘈杂，切换到外放")
                AudioUtils.changeToSpeaker(context)
                routeChangeListener?.onAudioRouteChanged(AudioRoute.SPEAKER)
            }
        }
    }

    /**
     * 更新蓝牙指示状态
     */
    private fun updateBluetoothIndication(bluetoothHeadsetState: Int) {
        when (bluetoothHeadsetState) {
            BluetoothProfile.STATE_CONNECTED -> {
                Loger.dTag(TAG, "蓝牙耳机已连接，切换到蓝牙")
                AudioUtils.changeToHeadset(context)
                routeChangeListener?.onAudioRouteChanged(AudioRoute.BLUETOOTH)
            }
            BluetoothProfile.STATE_DISCONNECTED -> {
                Loger.dTag(TAG, "蓝牙耳机已断开，切换到外放")
                AudioUtils.changeToSpeaker(context)
                routeChangeListener?.onAudioRouteChanged(AudioRoute.SPEAKER)
            }
        }
    }

    companion object {
        private const val TAG = "HeadsetPlugReceiver"
    }
}