package com.atmob.keyboard_android

import android.content.Context
import android.os.Build
import com.atmob.keyboard_android.floating.FloatingButtonService
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.LogUtil
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

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        context = flutterPluginBinding.applicationContext
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "keyboard_android")
        channel.setMethodCallHandler(this)
    }

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

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

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

            // 判断指定的输入法是否启用
            "isTargetKeyboardEnabled" -> {
                result.success(InputMethodUtil.isTargetKeyboardEnabled(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)
    }
}