package app.guru.guru_navigator

import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.NewIntentListener

/** GuruNavigatorPlugin */
class GuruNavigatorPlugin : FlutterPlugin, MethodCallHandler, NewIntentListener {

    companion object {
        object MethodNames {
            const val navigate = "navigate"
        }
    }

    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    private val handler = Handler(Looper.getMainLooper())

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "app.guru.guru_navigator")
//    channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
//    channel.setMethodCallHandler(null)
    }

    override fun onNewIntent(intent: Intent): Boolean {
        return handleIntent(intent)
    }

    private fun isDynamicLink(intent: Intent): Boolean {
        return intent.extras?.containsKey("com.google.firebase.dynamiclinks.DYNAMIC_LINK_DATA") == true
    }

    private fun handleIntent(intent: Intent): Boolean {
        val isDynamicLink = isDynamicLink(intent)
        Log.w(
            "MainActivity",
            "handleIntent extras:${intent.extras} dynamicLink:${isDynamicLink} data:${intent.data}"
        )

        // 如果是dynamicLink 这里直接忽略，交给Flutter层进行处理
        if (isDynamicLink) {
            return true
        }
        return intent.data?.let { uri ->
            Log.d("MainActivity", "handleIntent uri:$uri")
            handler.postDelayed({
                navigate(uri.toString())
            }, 100)
            return@let true
        } ?: false
    }

    private fun navigate(uri: String) {
        val params = hashMapOf<String, Any>("uri" to uri)
        channel.invokeMethod(MethodNames.navigate, params, null)
    }
}
