package com.zksy.gas.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.time.LocalDateTime;

public class ProtocolUtils {

    /**
     * BCD 转换为十进制
     */
    private static int bcdToInt(byte b) {
        return ((b >> 4) & 0x0F) * 10 + (b & 0x0F);
    }

    /**
     * 解析 6 字节 BCD 时间戳
     * 格式：YY MM DD HH mm ss
     */
    public static LocalDateTime parseTimestamp(byte[] frame, int offset) {
        int year = 2000 + bcdToInt(frame[offset]);
        int month = bcdToInt(frame[offset + 1]);
        int day = bcdToInt(frame[offset + 2]);
        int hour = bcdToInt(frame[offset + 3]);
        int minute = bcdToInt(frame[offset + 4]);
        int second = bcdToInt(frame[offset + 5]);
        return LocalDateTime.of(year, month, day, hour, minute, second);
    }



    /**
     * 小端序字节数组转 float
     */
    public static float bytesToFloatLE(byte[] bytes, int offset) {
        int bits = (bytes[offset] & 0xFF)
                | ((bytes[offset + 1] & 0xFF) << 8)
                | ((bytes[offset + 2] & 0xFF) << 16)
                | ((bytes[offset + 3] & 0xFF) << 24);
        return Float.intBitsToFloat(bits);
    }
    public static float readFloat6(byte[] frame, int offset) {
        // 小端转大端：取后4字节反转后再解析
        byte[] floatBytes = new byte[4];
        floatBytes[0] = frame[offset + 5];
        floatBytes[1] = frame[offset + 4];
        floatBytes[2] = frame[offset + 3];
        floatBytes[3] = frame[offset + 2];
        return ByteBuffer.wrap(floatBytes).order(ByteOrder.BIG_ENDIAN).getFloat();
    }
    /**
     * 字节数组转 Hex 字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    /**
     * 16进制字符串转字节数组
     */
    public static byte[] hexStringToBytes(String hex) {
        hex = hex.replaceAll("\\s+", "");
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }
}
