package net.northking.cctp.upperComputer.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

public class ByteUtils {
    private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);

    public static String byteToHex(byte b) {
        byte[] hexChars = new byte[2];
        int v = b & 0xFF;
        hexChars[0] = HEX_ARRAY[v >>> 4];
        hexChars[1] = HEX_ARRAY[v & 0x0F];
        return new String(hexChars, StandardCharsets.UTF_8);
    }

    public static String bytesToHex(byte[] bytes) {
        byte[] hexChars = new byte[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            hexChars[i * 2] = HEX_ARRAY[v >>> 4];
            hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars, StandardCharsets.UTF_8);
    }

    public static String bytesToIp(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            if (sb.length() > 0) {
                sb.append(".");
            }
            if (bytes.length > 4) {
                sb.append(byteToHex(b));
            } else {
                sb.append(b & (byte) 0xFF);
            }
        }
        return sb.toString();
    }

    public static byte[] hexStringToByteArray(String hexString) {
        if (hexString == null) return new byte[0];
        String fixString = hexString.trim().replace(" ", "");
        if (fixString.length() < 2) return new byte[0];
        byte[] byteArray = new byte[fixString.length() / 2];
        try {
            for (int i = 0; i < byteArray.length; i++) {
                int index = i * 2;
                int b = Integer.parseInt(fixString.substring(index, index + 2), 16);
                byteArray[i] = (byte) b;
            }
        } catch (NumberFormatException ignore) {

        }

        return byteArray;
    }

    /**
     * 小端在前的整型数据字节数组转换为java int，只能是四个字节长度。
     *
     * @param bytes 小端在前的整型数据字节数组
     * @return 数字
     */
    public static int littleEndianByteArrayToInt(byte[] bytes) {
        if (bytes.length != 4) {
            throw new NumberFormatException("参数长度应为4，实际为：" + bytes.length);
        }
        byte tmp = bytes[0];
        bytes[0] = bytes[3];
        bytes[3] = tmp;
        tmp = bytes[1];
        bytes[1] = bytes[2];
        bytes[2] = tmp;

        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        return buffer.getInt();
    }

    public static byte[] intToLittleEndianByteArray(int number) {
        ByteBuffer buffer = ByteBuffer.allocate(4);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.putInt(number);
        return buffer.array();
    }
}
