package com.aliyun.face.aliyun_face_plugin

import android.content.Context
import android.os.Build
import androidx.annotation.NonNull
import io.flutter.Log
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 com.alipay.face.api.ZIMCallback
import com.alipay.face.api.ZIMFacade
import com.alipay.face.api.ZIMFacadeBuilder
import com.alipay.face.api.ZIMResponse

/** AliyunFacePlugin */
class AliyunFacePlugin : FlutterPlugin, MethodCallHandler {
    /// 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 var mContext: Context? = null // Kotlin 空安全，默认 nullable
    private val TAG = "AliyunFace"

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "aliyun_face_plugin")
        channel.setMethodCallHandler(this)
        mContext = flutterPluginBinding.applicationContext
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("android ${Build.VERSION.RELEASE}")
            }
            "init" -> {
                Log.d(TAG, "enter init.")
                // 空安全检查：避免 mContext 为空导致崩溃
                mContext?.let { ZIMFacade.install(it) } ?: run {
                    Log.e(TAG, "Context is null when call init")
                    result.error("NULL_CONTEXT", "Context is null", null)
                }
            }
            "getMetaInfos" -> {
                Log.d(TAG, "enter getMetaInfos.")
                // 空安全处理
                val metaInfo = mContext?.let { ZIMFacade.getMetaInfos(it) } ?: ""
                result.success(metaInfo)
            }
            "verify" -> {
                Log.d(TAG, "enter verify.")
                // 处理参数：Kotlin 强类型转换 + 空安全
                val params = call.arguments as? Map<String, String>
                val certifyId = params?.get("certifyId")

                // 校验 certifyId 非空
                if (certifyId.isNullOrEmpty()) {
                    Log.e(TAG, "certifyId is null or empty")
                    result.error("INVALID_PARAM", "certifyId is null or empty", null)
                    return
                }

                // 空安全检查 Context
                val context = mContext ?: run {
                    Log.e(TAG, "Context is null when call verify")
                    result.error("NULL_CONTEXT", "Context is null", null)
                    return
                }

                // 构建 ZIMFacade 并调用验证
                val zimFacade = ZIMFacadeBuilder.create(context)
                zimFacade.verify(certifyId, false, object : ZIMCallback {
                    override fun response(response: ZIMResponse?): Boolean {
                        // 空安全处理 response
                        val code = response?.code ?: -1
                        val reason = response?.reason ?: "unknown error"

                        if (response != null && code == 1000) {
                            Log.d(TAG, "face verify success.")
                        } else {
                            Log.e(TAG, "face verify error. code: $code, reason: $reason")
                        }

                        // 返回结果给 Flutter
                        result.success("$code,$reason")
                        return true
                    }
                })
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        mContext = null // 释放 Context 引用，避免内存泄漏
    }
}