package com.atmob.keyboard_android

import android.content.Context
import android.os.Build
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.constant.PluginConfig
import com.atmob.keyboard_android.floating.FloatingButtonService
import com.atmob.keyboard_android.util.AppMonitor
import com.atmob.keyboard_android.util.ContextUtil
import com.atmob.keyboard_android.util.FloatingWindowUtil
import com.atmob.keyboard_android.util.InputMethodUtil
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
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/**
 * 键盘插件
 */
class KeyboardAndroidPlugin : FlutterPlugin, MethodCallHandler {
    private lateinit var channel: MethodChannel

    private lateinit var context: Context

    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) {
        context = flutterPluginBinding.applicationContext
        channel = MethodChannel(
            flutterPluginBinding.binaryMessenger,
            PluginConfig.FLUTTER_METHOD_CHANNEL_NAME
        )
        channel.setMethodCallHandler(this)

        LogUtil.d("KeyboardAndroidPlugin 初始化")
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        LogUtil.d("Method called: ${call.method}")
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("Android ${Build.VERSION.RELEASE}")
            }

            // 初始化插件
            "initPlugin" -> {
                // 注册键盘切换监听
                FlutterBridgeManager.registerDefaultKeyboardChangeEvent()
                result.success(null)
            }

            // 开启或关闭悬浮窗
            "enableFloatingWindow" -> {
                val enable = call.argument<Boolean>("enable") == true
                enableFloatingWindow(enable)
                result.success(null)
            }

            // 跳转到系统的悬浮窗设置页
            "jumpFloatingWindowSetting" -> {
                FloatingWindowUtil.jumpFloatingWindowSetting(context)
                result.success(null)
            }

            // 是否开启了悬浮窗权限
            "hasFloatingWindowPermission" -> {
                val hasPermission = FloatingWindowUtil.hasFloatingWindowPermission(context)
                result.success(hasPermission)
            }

            // 打开输入法设置
            "openInputMethodSettings" -> {
                InputMethodUtil.openInputMethodSettings(context)
                result.success(null)
            }

            // 判断指定的输入法是否启用
            "isTargetKeyboardEnabled" -> {
                result.success(InputMethodUtil.isTargetKeyboardEnabled(context))
            }

            // 是否是默认输入法
            "isDefaultKeyboard" -> {
                result.success(InputMethodUtil.isDefaultKeyboard(context))
            }

            else -> {
                result.notImplemented()
            }
        }
    }

    /**
     * 开启或关闭悬浮窗
     */
    private fun enableFloatingWindow(enable: Boolean) {
        if (enable) {
            FloatingButtonService.start(context)
        } else {
            FloatingButtonService.stop(context)
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}