package xn.hxp.util;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;

public class CardReaderHelper {
    private static final String TAG = "CardReader";
    private static final long TIMEOUT_THRESHOLD = 50; // 50ms无新事件视为刷卡结束

    private final StringBuilder currentString = new StringBuilder();
    private long lastEventTime = 0;
    private final Handler handler;
    private final OnCardReadListener listener;
    private final Runnable timeoutTask = this::dispatchResult;

    public interface OnCardReadListener {
        void onCardRead(String cardData);
    }

    public CardReaderHelper(OnCardReadListener listener) {
        this.listener = listener;
        this.handler = new Handler(Looper.getMainLooper());
    }

    public void handleKeyEvent(KeyEvent event) {
        // 1. 只处理按键按下事件
        if (event.getAction() != KeyEvent.ACTION_DOWN) return;

        // 2. 获取当前时间和字符
        long eventTime = event.getEventTime();
        char inputChar = convertKeyCodeToChar(event);
        if (inputChar == 0) return; // 忽略无效字符

        // 3. 判断是否新刷卡操作
        if (eventTime - lastEventTime > 100) { // 100ms间隔视为新操作
            currentString.setLength(0);
        }

        // 4. 追加字符并重置超时
        currentString.append(inputChar);
        lastEventTime = eventTime;
        resetTimeout();
    }

    private char convertKeyCodeToChar(KeyEvent event) {
        // 获取MetaState（处理Shift等修饰键）
        int metaState = event.getMetaState();

        // 转换为Unicode字符（支持数字/字母/符号）
        int unicodeChar = event.getUnicodeChar(metaState);

        // 过滤特殊功能键（如ENTER/BACK）
        if (unicodeChar >= 32 && unicodeChar <= 126) { // 可打印ASCII范围
            return (char) unicodeChar;
        }
        return 0;
    }

    private void resetTimeout() {
        handler.removeCallbacks(timeoutTask);
        handler.postDelayed(timeoutTask, TIMEOUT_THRESHOLD);
    }

    private void dispatchResult() {
        if (currentString.length() > 0) {
            Log.d(TAG, "Card read complete: " + currentString);
            if (listener != null) {
                listener.onCardRead(currentString.toString());
            }
            currentString.setLength(0);
        }
    }

    public void release() {
        handler.removeCallbacksAndMessages(null);
    }
}
