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.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 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 pasteInput(
            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) {
                editText.setText(clipData.getItemAt(0).text.toString())
                success?.invoke()
            } else {
                fail?.invoke()
            }
        }

        /**
         * 自定义键盘，点击输入法的按键，输入指定的文本
         */
        fun inputText(currentInputConnection: InputConnection, text: String) {
            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(currentInputConnection: InputConnection) {
            currentInputConnection.performEditorAction(EditorInfo.IME_ACTION_SEND)
        }
    }
}