package com.eventtan.test.penguin_flutter_sample

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.eventtan.app.penguin_flutter_sample.penguin.PenguinView
import com.eventtan.app.penguin_flutter_sample.penguin.PenguinViewFactory
import com.eventtan.test.penguin_flutter_sample.PermissionManager.PermissionHelper
import com.eventtan.test.penguin_flutter_sample.PermissionManager.PermissionManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel


/**
 * The main activity for the Flutter application.
 * This activity is responsible for configuring the Flutter engine and registering platform view factories.
 */
class MainActivity : FlutterActivity() {



    private lateinit var flutterEngine: FlutterEngine

    private val CHANNEL = "com.aamir/launch_penguin_ui"

    /**
     * Configures the Flutter engine by registering platform view factories.
     *
     * @param flutterEngine The [FlutterEngine] instance associated with this activity.
     */
    @RequiresApi(Build.VERSION_CODES.O)
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)



        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
                call, result ->
            when (call.method) {
                "launchPenguin" -> {
                    print("the platform channel is being called" )
                    val args = call.arguments as Map<String, String>?
                    Log.d("TAG", "configureFlutterEngine: $args")
                    println("args")
                    args?.let {
                        PenguinView(activity,100,args,flutterEngine.dartExecutor.binaryMessenger  , activity = this,)
                    }
                }
            }
        }
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)

        val granted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }

        val intent = Intent("PERMISSION_RESULT_ACTION").apply {
            putExtra("PERMISSION_GRANTED", granted)
        }
        sendBroadcast(intent)

        // Log the request code and permission results
        Log.d("PermissionsResult", "Request Code: $requestCode")
        Log.d("PermissionsResult", "Permissions: ${permissions.joinToString()}")
        Log.d("PermissionsResult", "Grant Results: ${grantResults.joinToString()}")

    }


}

