package com.example.environment_monitoring_app

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity: FlutterActivity() {
    // This channel name must match the one used in your Dart code (e.g., in the InSituSamplingService).
    private val CHANNEL = "com.example.environment_monitoring_app/usb"
    private val ACTION_USB_PERMISSION = "com.example.environment_monitoring_app.USB_PERMISSION"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            // This block listens for method calls from your Flutter app.
            if (call.method == "requestUsbPermission") {
                val manager = getSystemService(Context.USB_SERVICE) as UsbManager
                var deviceToRequest: UsbDevice? = null

                // Get the Vendor ID and Product ID sent from the Dart code.
                val vid = call.argument<Int>("vid")
                val pid = call.argument<Int>("pid")

                // Find the matching USB device connected to the phone.
                manager.deviceList.values.forEach { device ->
                    if (device.vendorId == vid && device.productId == pid) {
                        deviceToRequest = device
                    }
                }

                deviceToRequest?.let {
                    // If the device is found, create an intent and request permission from the user.
                    // The 'usb_serial' package in Flutter will listen for the result of this permission request.
                    val usbPermissionIntent = PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_IMMUTABLE)
                    manager.requestPermission(it, usbPermissionIntent)
                    result.success(true) // Inform Dart that the request was successfully sent.
                } ?: run {
                    // If the device is not found, send an error back to Dart.
                    result.error("DEVICE_NOT_FOUND", "Specified USB device not found.", null)
                }
            } else {
                result.notImplemented()
            }
        }
    }
}
