package com.atmob.keyboard_android.util

import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
import android.content.Intent
import android.inputmethodservice.InputMethodService
import android.os.Build
import android.os.IBinder
import android.provider.Settings
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import android.widget.EditText


/**
 * 输入法工具类
 */
class InputMethodUtil private constructor() {
    companion object {
        /**
         * 显示输入法选择器
         */
        fun showInputMethodPicker(context: Context) {
            val inputMethodManager =
                context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.showInputMethodPicker()
        }

        /**
         * 打开输入法设置
         */
        fun openInputMethodSettings(context: Context) {
            val intent = Intent(Settings.ACTION_INPUT_METHOD_SETTINGS)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        }

        /**
         * 判断指定的输入法是否启用
         */
        fun isTargetKeyboardEnabled(context: Context): Boolean {
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val enabledInputMethods = imm.enabledInputMethodList
            return enabledInputMethods.any { it.packageName == context.packageName }
        }

        /**
         * 我的自定义输入法，是否是默认输入法
         */
        fun isDefaultKeyboard(context: Context): Boolean {
            val currentInputMethodId = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.DEFAULT_INPUT_METHOD
            )
            return currentInputMethodId != null && currentInputMethodId.contains(context.packageName)
        }

        /**
         * 粘贴文本到自己的输入框中
         */
        fun pasteText2EditText(
            editText: EditText,
            success: (() -> Unit)? = null,
            fail: (() -> Unit)? = null
        ) {
            val clipboard = editText.context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            val clipData = clipboard.primaryClip
            if (clipData != null && clipData.itemCount > 0) {
                val text = clipData.getItemAt(0).text.toString()
                editText.setText(text)
                success?.invoke()
            } else {
                fail?.invoke()
            }
        }

        /**
         * 自定义键盘，点击输入法的按键，输入指定的文本
         *
         * @param isNeedClear 是否需要清空原有的内容
         */
        fun inputText(
            currentInputConnection: InputConnection,
            text: String,
            isNeedClear: Boolean = true
        ) {
            if (isNeedClear) {
                clearInput(currentInputConnection)
            }
            currentInputConnection.commitText(text, 1)
        }

        /**
         * 自定义键盘，点击删除按钮，删除文本
         */
        fun deleteInput(currentInputConnection: InputConnection) {
            currentInputConnection.deleteSurroundingText(1, 0)
        }

        /**
         * 自定义键盘，点击清空按钮，清空所有文本
         */
        fun clearInput(currentInputConnection: InputConnection) {
            currentInputConnection.deleteSurroundingText(
                Int.MAX_VALUE,
                Int.MAX_VALUE
            )
        }

        /**
         * 自定义键盘，点击发送按钮，触发发送行为
         */
        fun clickSendBtn(inputMethodService: InputMethodService) {
            inputMethodService.currentInputConnection.performEditorAction(EditorInfo.IME_ACTION_SEND)
        }

        /**
         * 隐藏键盘
         */
        fun hideKeyboard(inputMethodService: InputMethodService) {
            val windowToken = getInputMethodWindowToken(inputMethodService)
            if (windowToken == null) {
                return
            }

            val context = inputMethodService.applicationContext
            val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(windowToken, 0)

            // 结束当前输入会话
            inputMethodService.onFinishInput()
        }

        /**
         * 保持输入法显示
         */
        fun keepKeyboardShow(inputMethodService: InputMethodService) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                inputMethodService.requestShowSelf(0)
            } else {
                // 对于较低版本，尝试通过InputMethodManager重新显示键盘
                val imm =
                    inputMethodService.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                val view = inputMethodService.window.window?.decorView
                view?.post {
                    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
                }
            }
        }

        /**
         * 获取InputMethodService的WindowToken
         */
        private fun getInputMethodWindowToken(inputMethodService: InputMethodService): IBinder? {
            val dialog = inputMethodService.window
            return dialog.window?.decorView?.windowToken
        }
    }
}