package com.dlc.eboard.serial

import android.view.KeyEvent
import java.lang.StringBuilder

/**
 * info
 *
 * @author ReiChin_
 */
class ScanKeyEventHelper(private val callback: ((content: String) -> Unit)? = null) {

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

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

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

        if (KeyEvent.KEYCODE_ENTER == keyCode) {
            if (mKeyContent.isNotEmpty()) callback?.invoke(mKeyContent.toString())
            mKeyContent.clear()
        } else {
            decodeKeyCode(keyCode)?.let { keyChar ->
                mKeyContent.append(keyChar)
            }
        }

    }

    private fun decodeKeyCode(keyCode: Int): Char? {
        return when (keyCode) {
            in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> {
                // 0:48=0x30
                return (keyCode - KeyEvent.KEYCODE_0 + 0x30).toChar()
            }
            in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z -> {
                // a:97=0x61 A:65=0x41
                return (keyCode - KeyEvent.KEYCODE_A + if (mCaps) 0x41 else 0x61).toChar()
            }
//            KeyEvent.KEYCODE_PERIOD -> '.'
//            KeyEvent.KEYCODE_MINUS -> if (mCaps) '_' else '-'
//            KeyEvent.KEYCODE_SLASH -> '/'
//            KeyEvent.KEYCODE_BACKSLASH -> if (mCaps) '|' else '\\'
            else -> null
        }
    }

}