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.CopyOnWriteArrayList

/**
 * 原生端方法注册表，提供方法给Flutter端
 */
class NativeMethodRegistry {
    /**
     * 方法注册列表
     */
    private val mMethodList = CopyOnWriteArrayList<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 callArgs: Any? = call.arguments
            // 查找到方法处理器
            for (methodHandler in mMethodList) {
                if (methodHandler.isCanHandle(methodName)) {
                    methodHandler.onMethodCall(methodName, callArgs, object : ResultCallback {
                        override fun onSuccess(data: Any?) {
                            result.success(data)
                        }

                        override fun onFail(errorCode: Int, errorMsg: String) {
                            result.error(errorCode.toString(), errorMsg, null)
                        }

                        override fun onMethodNotFound() {
                            result.notImplemented()
                        }
                    })
                }
            }
        }
    }

    /**
     * 注册原生方法
     */
    fun registerNativeMethod(methodHandler: NativeMethodHandler) {
        if (!mMethodList.contains(methodHandler)) {
            mMethodList.add(methodHandler)
        }
    }

    /**
     * 取消注册原生方法
     */
    fun unRegisterNativeMethod(methodHandler: NativeMethodHandler) {
        mMethodList.remove(methodHandler)
    }
}