package com.example.absenkuv3.broadcast


import android.content.Context
import android.os.Build
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel


class EventChannelHandler(val context: Context) {
    fun startListening(flutterEngine: FlutterEngine, channel: String, tag: String) {
        EventChannel(flutterEngine.dartExecutor, channel).setStreamHandler(
            object : EventChannel.StreamHandler {
                val receiver = BroadcastReceiverHandler()
                override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink) {

                    receiver.setListener(object : BroadcastReceiverHandlerListener() {
                        override fun onReportCamera(detail: String?) {
                            Log.i(tag, "Success Reported Camera: $detail")
                            eventSink.success(detail)
                        }
                    })
                    val filter = IntentFilter("action.REPORT_CAMERA")
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                context.registerReceiver(receiver, filter, Context.RECEIVER_EXPORTED)
                        }else {
                                context.registerReceiver(receiver, filter)
                        }
                }
                override fun onCancel(arguments: Any?) {
                    context.unregisterReceiver(receiver)
                }
            }
        )
    }

    fun onReportCameraClicked(context: Context, tag: String, data: HashMap<String, String>) {
        Log.i(tag, "Report Camera Clicked")
        val bundle = Bundle()
        for ((key, value) in data) {
            bundle.putString(key, value)
        }
        Intent().also { intent ->
            intent.action = "action.REPORT_CAMERA"
            intent.putExtra("reportCamera", bundle)
            context.sendBroadcast(intent)
        }
    }

}