package xn.hxp.receiver

import android.view.KeyEvent

/**
 * 外置超高频RFID读卡器专用KeyEvent解析器
 * 与ScanKeyEventHelper类似，但：
 * 1. 收到ENTER时仅回调内容，不传递enter给视图
 * 2. 不设置超时自动提交（超高频RFID读卡器是快速连续输入+enter结尾）
 */
class UhfRfidKeyEventHelper(private val callback: ((content: String) -> Unit)? = null) {

    private var mCaps = false
    private val mKeyContent = StringBuilder()

    fun analysisKeyEvent(event: KeyEvent): Boolean {
        val keyCode = event.keyCode
        if (KeyEvent.KEYCODE_SHIFT_RIGHT == keyCode || KeyEvent.KEYCODE_SHIFT_LEFT == keyCode) {
            mCaps = KeyEvent.ACTION_DOWN == event.action
            return true
        }

        if (KeyEvent.ACTION_DOWN != event.action) return true

        if (KeyEvent.KEYCODE_ENTER == keyCode || KeyEvent.KEYCODE_NUMPAD_ENTER == keyCode) {
            if (mKeyContent.isNotEmpty()) {
                callback?.invoke(mKeyContent.toString())
            }
            mKeyContent.clear()
            return true // 消费掉enter，不传递给视图
        } else {
            decodeKeyCode(keyCode, event)?.let { keyChar ->
                mKeyContent.append(keyChar)
            }
            return true
        }
    }

    fun clear() {
        mKeyContent.clear()
    }

    private fun decodeKeyCode(keyCode: Int, event: KeyEvent): Char? {
        val isShiftPressed = event.isShiftPressed
        if (keyCode in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9) {
            return (keyCode - KeyEvent.KEYCODE_0 + 0x30).toChar()
        } else if (keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z) {
            return (keyCode - KeyEvent.KEYCODE_A + if (isShiftPressed) 0x41 else 0x61).toChar()
        } else if (keyCode == KeyEvent.KEYCODE_PERIOD) {
            return '.'
        } else if (keyCode == KeyEvent.KEYCODE_MINUS) {
            return if (isShiftPressed) '_' else '-'
        } else if (keyCode == KeyEvent.KEYCODE_SLASH) {
            return '/'
        } else if (keyCode == KeyEvent.KEYCODE_BACKSLASH) {
            return if (isShiftPressed) '|' else '\\'
        } else if (keyCode == KeyEvent.KEYCODE_EQUALS) {
            return '='
        }
        return null
    }
}
