package com.atmob.keyboard_android

import com.atmob.keyboard_android.component.ComponentMediator
import com.atmob.keyboard_android.component.base.interceptor.LoginRouteInterceptor
import com.atmob.keyboard_android.component.base.interceptor.RouteInterceptorManager
import com.atmob.keyboard_android.component.listener.ComponentUpdateLoggingListener
import com.atmob.keyboard_android.util.AppMonitor
import com.atmob.keyboard_android.util.ContextUtil
import com.atmob.keyboard_android.util.FlutterEngineHolder
import com.atmob.keyboard_android.util.LogUtil
import com.atmob.keyboard_android.util.activity.ActivityProvider
import com.atmob.keyboard_android.util.bridge.FlutterBridgeManager
import io.flutter.embedding.engine.plugins.FlutterPlugin

/**
 * 键盘插件
 */
class KeyboardAndroidPlugin : FlutterPlugin {
    companion object {
        init {
            // 伴生对象的初始化，相当于Java的静态代码块，只初始化一次
            initActivityUtil()
            initComponentApi()
        }

        /**
         * 初始化Activity工具类
         */
        private fun initActivityUtil() {
            ActivityProvider.initialize()
            AppMonitor.get().initialize(ContextUtil.getContext())
//            AppMonitor.get().register(object : AppMonitor.CallbackAdapter() {
//                override fun onAppUIDestroyed() {
//                    super.onAppUIDestroyed()
//                    // 所有Activity页面都销毁了，静默让Flutter跳转去启动页
//                    FlutterBridgeManager.jump2SplashPage(quiesceJump = true)
//                }
//            })
        }

        /**
         * 初始化组件相关Api
         */
        @JvmStatic
        private fun initComponentApi() {
            // 注册组件更新监听器
            ComponentMediator.setOnComponentUpdateListener(ComponentUpdateLoggingListener())
            // 登录拦截器
            RouteInterceptorManager.registerInterceptor(LoginRouteInterceptor())
        }
    }

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        FlutterEngineHolder.attachFlutterEngine(
            flutterPluginBinding.flutterEngine
        )
        // 暴露给Flutter的原生方法
        FlutterBridgeManager.exposeKeyboardOptMethod()
        LogUtil.d("KeyboardAndroidPlugin 注册到引擎，onAttachedToEngine()")
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        // 取消暴露给Flutter的原生方法
        FlutterBridgeManager.cancelExposeKeyboardOptMethod()
        FlutterEngineHolder.detachFlutterEngine()
        LogUtil.d("KeyboardAndroidPlugin 从引擎中注销，onDetachedFromEngine()")
    }
}