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

import com.atmob.keyboard_android.constant.PluginConfig
import com.atmob.keyboard_android.util.DefaultKeyboardWatcher
import com.atmob.keyboard_android.util.bridge.callback.NativeEventEmitter
import com.atmob.keyboard_android.util.bridge.callback.NativeEventHandler
import java.util.concurrent.CopyOnWriteArrayList

/**
 * 默认键盘切换事件处理器
 */
class DefaultKeyboardNativeEventHandler : NativeEventHandler {
    /**
     * 事件发射器列表
     */
    private var mNativeEventEmitters: MutableList<NativeEventEmitter> = CopyOnWriteArrayList()

    /**
     * 默认键盘切换监听
     */
    private val mOnKeyboardChangeListener =
        object : DefaultKeyboardWatcher.OnDefaultKeyboardChangeListener {
            override fun onDefaultKeyboard() {
                for (emitter in mNativeEventEmitters) {
                    emitter.success(true)
                }
            }

            override fun onNotDefaultKeyboard() {
                for (emitter in mNativeEventEmitters) {
                    emitter.success(false)
                }
            }
        };

    override fun onGetEventChannelName(): String {
        return PluginConfig.FLUTTER_DEFAULT_KEYBOARD_EVENT_CHANNEL_NAME
    }

    override fun onRegisterEventListener(
        args: String,
        emitter: NativeEventEmitter
    ) {
        if (!mNativeEventEmitters.contains(emitter)) {
            mNativeEventEmitters.add(emitter)
        }
        // 没有初始化，则先初始化
        if (!DefaultKeyboardWatcher.isInited()) {
            DefaultKeyboardWatcher.init()
        }
        DefaultKeyboardWatcher.registerListener(mOnKeyboardChangeListener)
    }

    override fun onUnRegisterEventListener(args: String, emitter: NativeEventEmitter) {
        mNativeEventEmitters.remove(emitter)
        DefaultKeyboardWatcher.unRegisterListener(mOnKeyboardChangeListener)
    }
}