package com.sunny.app.soft.timberkeyboardnew.service

import android.inputmethodservice.InputMethodService
import android.inputmethodservice.Keyboard
import android.inputmethodservice.KeyboardView
import android.os.SystemClock
import android.text.InputType
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import com.sunny.app.soft.timberkeyboardnew.App
import com.sunny.app.soft.timberkeyboardnew.R
import com.sunny.app.soft.timberkeyboardnew.databinding.ViewInputBinding
import com.sunny.app.soft.timberkeyboardnew.tools.AppConstant
import com.sunny.app.soft.timberkeyboardnew.tools.ZipTools


class KeyboardService : InputMethodService(), KeyboardView.OnKeyboardActionListener {

    private lateinit var binding: ViewInputBinding
    private val views =
        intArrayOf(R.xml.keyboard_letter, R.xml.keyboard_number, R.xml.keyboard_symbol)
    private var mouble = false
    private var laTime = -3L

    private var curImeAction = EditorInfo.IME_ACTION_UNSPECIFIED

    private var imm: InputMethodManager? = null

    private fun keyCase(toBig: Boolean, keyboard: Keyboard) {
        for (key in keyboard.keys) {
            if (!key.label.isNullOrEmpty()) {
                if (key.label.length == 1) {
                    var strin: Char = if (toBig) {
                        key.label.toString()[0].uppercaseChar()
                    } else {
                        key.label.toString()[0].lowercaseChar()
                    }
                    key.run {
                        label = strin.toString()
                        codes[0] = strin.code
                    }
                }
            }
        }
    }

    private fun changeXml(mode: Int) {
        binding.myCustomInput.run {
            when (mode) {
                0 -> {
                    xmlMode = AppConstant.xml0
                    keyboard = Keyboard(context, views[0])
                }

                2 -> {
                    xmlMode = AppConstant.xml2
                    keyboard = Keyboard(context, views[2])

                }

                1 -> {
                    xmlMode = AppConstant.xml1
                    keyboard = Keyboard(context, views[1])
                }
            }
        }
    }


    override fun onCreateInputView(): View {
        binding = ViewInputBinding.inflate(layoutInflater, null, false)
        binding.myCustomInput.setOnKeyboardActionListener(this)
        binding.myCustomInput.run {
            keyboard = Keyboard(this@KeyboardService, views[0])
            isEnabled = true
        }
        imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        return binding.root
    }


    override fun onWindowShown() {
        super.onWindowShown()



        curImeAction = ZipTools.getTextForImeAction(currentInputEditorInfo.imeOptions)




        Log.d(App.TAG, "=======${curImeAction}")


        binding.myCustomInput.upUi(this@KeyboardService, curImeAction)
    }


    override fun onPress(primaryCode: Int) {
        mouble = false
        if (primaryCode == Keyboard.KEYCODE_SHIFT) {
            if (300 > SystemClock.elapsedRealtime() - laTime) {
                mouble = true
            }
            laTime = SystemClock.elapsedRealtime()
        }
    }


    override fun onRelease(primaryCode: Int) {
    }

    override fun onKey(primaryCode: Int, keyCodes: IntArray?) {

        when (primaryCode) {
            Keyboard.KEYCODE_SHIFT -> {
                binding.myCustomInput.run {
                    val myKeyboard = keyboard
                    when (shiftStatus) {
                        AppConstant.Shift_S -> {
                            shiftStatus = if (mouble) {
                                AppConstant.Shift_B_lo
                            } else {
                                AppConstant.Shift_B
                            }
                            keyCase(true, myKeyboard)
                            keyboard = myKeyboard
                        }

                        AppConstant.Shift_B_lo -> {
                            shiftStatus = AppConstant.Shift_S
                            keyCase(false, myKeyboard)
                            keyboard = myKeyboard
                        }

                        AppConstant.Shift_B -> {
                            shiftStatus = if (mouble) {
                                AppConstant.Shift_B_lo
                            } else {
                                keyCase(false, myKeyboard)
                                AppConstant.Shift_S
                            }
                            keyboard = myKeyboard
                        }
                    }
                }
            }

            // 点击完成/回车/搜索
            Keyboard.KEYCODE_DONE -> {

                currentInputConnection.performEditorAction(curImeAction)
                when (curImeAction) {
                    EditorInfo.IME_ACTION_NONE -> null
                    EditorInfo.IME_ACTION_GO -> "go"
                    EditorInfo.IME_ACTION_SEARCH -> {
//                        Log.d(App.TAG, "=======IME_ACTION_SEARCH")

                    }
                    EditorInfo.IME_ACTION_SEND -> "send"
                    EditorInfo.IME_ACTION_NEXT -> "next"
                    EditorInfo.IME_ACTION_DONE -> {
//                        Log.d(App.TAG, "=======IME_ACTION_DONE")

                    }
                    EditorInfo.IME_ACTION_PREVIOUS -> "previous"
                    else -> {
//                        Log.d(App.TAG, "=======IME_ACTION_DONE")

                    }

                }

            }

            Keyboard.KEYCODE_MODE_CHANGE -> {
                binding.myCustomInput.run {
                    if (xmlMode == AppConstant.xml0) {
                        changeXml(1)
                    } else {
                        changeXml(0)
                    }
                }
            }

            AppConstant.SHIFT_NUMBER -> {
                changeXml(2)
            }

            Keyboard.KEYCODE_DELETE -> {
                currentInputConnection.deleteSurroundingText(1, 0)
            }

            AppConstant.SHIFT_SYMBOL -> {
                changeXml(1)
            }

            else -> {
                currentInputConnection.commitText(primaryCode.toChar().toString(), 1)
                binding.myCustomInput.keyboard = binding.myCustomInput.apply {
                    if (shiftStatus == AppConstant.Shift_B) {
                        shiftStatus = AppConstant.Shift_S
                        keyCase(false, binding.myCustomInput.keyboard)
                    }
                }.keyboard
            }

        }

    }

    override fun onText(text: CharSequence?) {

    }

    override fun swipeLeft() {

    }

    override fun swipeRight() {

    }

    override fun swipeDown() {

    }

    override fun swipeUp() {

    }
}