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


import com.atmob.keyboard_android.util.bridge.util.PluginInitializer
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.CopyOnWriteArrayList

/**
 * 代理MethodChannel，处理Flutter端方法还未初始化时，将调用任务延迟到初始化完成后再执行
 */
class ProxyMethodChannel(messenger: BinaryMessenger, name: String) :
    MethodChannel(messenger, name) {
    private val mPendingTaskQueue = CopyOnWriteArrayList<Runnable>()

    init {
        // 添加初始化监听
        PluginInitializer.addPluginInitListener(object : PluginInitializer.PluginInitListener {
            override fun onPluginInitComplete() {
                // 初始化完毕，执行待执行的任务
                for (task in mPendingTaskQueue) {
                    task.run()
                }
                mPendingTaskQueue.clear()
            }
        })
    }

    override fun invokeMethod(method: String, arguments: Any?, callback: Result?) {
        if (PluginInitializer.isPluginInitComplete()) {
            super.invokeMethod(method, arguments, callback)
        } else {
            mPendingTaskQueue.add(Runnable {
                super.invokeMethod(method, arguments, callback)
            })
        }
    }
}