package com.tsystems.flutter_vosk_wakeword

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.core.content.ContextCompat

/**
 * Service 和 Plugin 之间安全地传递事件
 */
class EventReceiver(private val onEvent: (type: String, text: String?) -> Unit) : BroadcastReceiver() {

    companion object {
        private const val ACTION_WAKEWORD_EVENT = "com.tsystems.flutter_vosk_wakeword.WAKEWORD_EVENT"
        private const val EXTRA_EVENT_TYPE = "EXTRA_EVENT_TYPE"
        private const val EXTRA_EVENT_TEXT = "EXTRA_EVENT_TEXT"

        fun broadcastPartial(context: Context, text: String) = broadcast(context, "partial", text)
        fun broadcastFinal(context: Context, text: String) = broadcast(context, "finalResult", text)
        fun broadcastWakeWord(context: Context, text: String) = broadcast(context, "wakeword", text)
        fun broadcastError(context: Context, text: String) = broadcast(context, "error", text)

        private fun broadcast(context: Context, type: String, text: String?) {
            val intent = Intent(ACTION_WAKEWORD_EVENT).apply {
                setPackage(context.packageName)
                putExtra(EXTRA_EVENT_TYPE, type)
                putExtra(EXTRA_EVENT_TEXT, text)
            }
            context.sendBroadcast(intent)
        }
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val type = intent?.getStringExtra(EXTRA_EVENT_TYPE)
        val text = intent?.getStringExtra(EXTRA_EVENT_TEXT)
        if (type != null) {
            onEvent(type, text)
        }
    }

    fun register(context: Context) {
        ContextCompat.registerReceiver(
            context,
            this,
            IntentFilter(ACTION_WAKEWORD_EVENT),
            ContextCompat.RECEIVER_NOT_EXPORTED
        )
    }

    fun unregister(context: Context) {
        context.unregisterReceiver(this)
    }
}