package com.atmob.keyboard_android.util.bridge.util

import com.atmob.keyboard_android.constant.PluginConfig
import com.atmob.keyboard_android.util.bridge.callback.NativeMethodHandler
import com.atmob.keyboard_android.util.bridge.callback.ResultCallback
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.ConcurrentHashMap

/**
 * 原生端方法注册表，提供方法给Flutter端
 */
class NativeMethodRegistry {
    /**
     * 注册表
     */
    private val mMethodMap = ConcurrentHashMap<String, NativeMethodHandler>()

    /**
     * 用于与 Flutter 端通信的 MethodChannel
     */
    private lateinit var mMethodChannel: MethodChannel

    /**
     * 初始化
     */
    fun init(engine: FlutterEngine) {
        mMethodChannel = MethodChannel(
            engine.dartExecutor.binaryMessenger,
            PluginConfig.FLUTTER_METHOD_CHANNEL_NAME
        )
        // 注册方法给Flutter
        mMethodChannel.setMethodCallHandler { call: MethodCall, result: MethodChannel.Result ->
            // 方法名
            val methodName = call.method
            // 方法参数
            val args = call.arguments<String>() ?: ""
            // 通过方法名，查找到方法处理器
            val nativeMethodHandler = mMethodMap[methodName]
            nativeMethodHandler?.onMethodCall(methodName, args, object : ResultCallback {
                override fun onSuccess(data: Any) {
                    result.success(data)
                }

                override fun onFail() {
                    result.error("-1", "error", null)
                }
            })
        }
    }

    /**
     * 注册原生方法
     */
    fun registerNativeMethod(methodName: String, methodHandler: NativeMethodHandler) {
        mMethodMap[methodName] = methodHandler
    }

    /**
     * 取消注册原生方法
     */
    fun unRegisterNativeMethod(methodName: String) {
        mMethodMap.remove(methodName)
    }
}