package com.atmob.keyboard_android.util.bridge.method

import android.content.Context
import android.os.Build
import com.atmob.keyboard_android.floating.FloatingButtonService
import com.atmob.keyboard_android.util.ContextUtil
import com.atmob.keyboard_android.util.InputMethodUtil
import com.atmob.keyboard_android.util.JsonUtil
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.LogUtil
import com.atmob.keyboard_android.util.bridge.FlutterBridgeManager
import com.atmob.keyboard_android.util.bridge.callback.NativeMethodHandler
import com.atmob.keyboard_android.util.bridge.callback.ResultCallback
import com.atmob.keyboard_android.util.bridge.enums.ExposeNativeMethod
import com.atmob.keyboard_android.util.bridge.model.resp.KeyboardInfo
import com.atmob.keyboard_android.util.flow.FloatingWindowUtil

/**
 * 键盘，暴露给Flutter的原生方法处理器
 */
class KeyboardExposeNativeMethodHandler : NativeMethodHandler {
    override fun isCanHandle(methodName: String): Boolean {
        return true
    }

    override fun onMethodCall(
        methodName: String,
        args: Any?,
        resultCallback: ResultCallback
    ) {
        LogUtil.d("Method called: $methodName")

        val context = ContextUtil.getContext()

        // 参数
        val callArgs = if (args is String) {
            args.toString()
        } else if (args is Map<*, *>) {
            JsonUtil.toJson(args)
        } else {
            null
        }

        when (methodName) {
            // 获取平台版本
            ExposeNativeMethod.GET_PLATFORM_VERSION.methodName -> {
                resultCallback.onSuccess("${Build.VERSION.RELEASE}")
            }

            // 初始化插件
            ExposeNativeMethod.INIT_PLUGIN.methodName -> {
                // 注册键盘切换监听
                FlutterBridgeManager.registerDefaultKeyboardChangeEvent()
                resultCallback.onSuccess(null)
            }

            // 开启或关闭悬浮窗
            ExposeNativeMethod.ENABLE_FLOATING_WINDOW.methodName -> {
                if (callArgs == null || callArgs.isBlank()) {
                    resultCallback.onFail(-1, "args is null")
                    return
                }
                val argsMap = JsonUtil.parseJsonByClass(callArgs.toString(), Map::class.java)
                val enable = argsMap["enable"] == true
                enableFloatingWindow(context, enable)
                resultCallback.onSuccess(null)
            }

            // 跳转到系统的悬浮窗设置页
            ExposeNativeMethod.JUMP_FLOATING_WINDOW_SETTING.methodName -> {
                FloatingWindowUtil.tryJumpToPermissionPage(context)
                resultCallback.onSuccess(null)
            }

            // 是否开启了悬浮窗权限
            ExposeNativeMethod.HAS_FLOATING_WINDOW_PERMISSION.methodName -> {
                val hasPermission = FloatingWindowUtil.hasFloatingWindowPermission(context)
                resultCallback.onSuccess(hasPermission)
            }

            // 打开输入法设置
            ExposeNativeMethod.OPEN_INPUT_METHOD_SETTINGS.methodName -> {
                InputMethodUtil.openInputMethodSettings(context)
                resultCallback.onSuccess(null)
            }

            // 判断指定的输入法是否启用
            ExposeNativeMethod.IS_TARGET_KEYBOARD_ENABLED.methodName -> {
                resultCallback.onSuccess(InputMethodUtil.isTargetKeyboardEnabled(context))
            }

            // 是否是默认输入法
            ExposeNativeMethod.IS_DEFAULT_KEYBOARD.methodName -> {
                resultCallback.onSuccess(InputMethodUtil.isDefaultKeyboard(context))
            }

            // 更新键盘信息
            ExposeNativeMethod.UPDATE_KEYBOARD_INFO.methodName -> {
                val keyboardInfoJson = callArgs ?: ""
                if (keyboardInfoJson.isBlank()) {
                    resultCallback.onSuccess(null)
                    return
                }
                val currentKeyboardInfo =
                    JsonUtil.parseJsonByClass(keyboardInfoJson, KeyboardInfo::class.java)
                KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
                    ?.updateCurrentKeyboardInfo(currentKeyboardInfo)
                resultCallback.onSuccess(null)
            }

            // 刷新人设列表
            ExposeNativeMethod.REFRESH_CHARACTER_LIST.methodName -> {
                LogUtil.d("刷新人设列表")
                KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()
                    ?.getCharacterList()
                resultCallback.onSuccess(null)
            }

            // 登录成功\退出登录\注销账号,刷新用户数据
            ExposeNativeMethod.REFRESH_DATA.methodName -> {
                KeyboardHolder.getKeyboardService()?.getKeyboardViewModel()?.run {
                    // 刷新数据
                    getCurrentKeyboardInfo()
                    getKeyboardList()
                    getCharacterList()
                    getPrologueList()
                }
                resultCallback.onSuccess(null)
            }

            else -> {
                resultCallback.onMethodNotFound()
            }
        }
    }

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