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

import com.atmob.keyboard_android.util.bridge.callback.NativeEventEmitter
import com.atmob.keyboard_android.util.bridge.callback.NativeEventHandler
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.EventChannel.EventSink
import io.flutter.plugin.common.EventChannel.StreamHandler
import java.util.concurrent.ConcurrentHashMap

/**
 * 原生端，发送事件给Flutter端，例如定位、默认键盘监听等功能
 */
class NativeEventRegistry {
    /**
     * Flutter引擎
     */
    private var mEngine: FlutterEngine? = null

    /**
     * 注册表，保存通道名称和通道的映射关系
     */
    private val mEventChannelMap = ConcurrentHashMap<String, EventChannel>()

    /**
     * 初始化
     */
    fun init(engine: FlutterEngine) {
        this.mEngine = engine
    }

    /**
     * 注册原生事件处理器
     */
    fun registerNativeEvent(eventChannelName: String, handler: NativeEventHandler) {
        if (mEngine == null) {
            throw IllegalArgumentException("请先调用init方法进行初始化")
        }

        val eventChannel = EventChannel(mEngine!!.dartExecutor.binaryMessenger, eventChannelName)
        eventChannel.setStreamHandler(object : StreamHandler {
            // 原生事件发射器
            private var nativeEventEmitter: NativeEventEmitter? = null

            override fun onListen(arguments: Any?, eventSink: EventSink) {
                nativeEventEmitter = object : NativeEventEmitter {
                    override fun success(event: Any) {
                        // 发射成功事件
                        eventSink.success(event)
                    }

                    override fun error(
                        errorCode: String,
                        errorMsg: String,
                        details: Any?
                    ) {
                        // 发送错误事件
                        eventSink.error(errorCode, errorMsg, details)
                    }

                    override fun eventStreamClose() {
                        // 通知事件流关闭
                        eventSink.endOfStream()
                    }
                }
                // Flutter端注册监听
                handler.onRegisterEventListener(arguments?.toString() ?: "", nativeEventEmitter!!)
            }

            override fun onCancel(arguments: Any?) {
                if (nativeEventEmitter == null) {
                    return
                }
                // Flutter端取消监听
                handler.onUnRegisterEventListener(arguments?.toString() ?: "", nativeEventEmitter!!)
            }
        })
        mEventChannelMap.put(eventChannelName, eventChannel)
    }

    /**
     * 取消注册原生事件处理器
     */
    fun unRegisterNativeEvent(eventChannelName: String) {
        val eventChannel = mEventChannelMap[eventChannelName]
        eventChannel?.setStreamHandler(null)
    }
}