package com.pwt.netty.util;

import io.netty.buffer.ByteBuf;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MessageUtil {

    public static String convertByteBufToString(ByteBuf buf) throws UnsupportedEncodingException {
        String str;
        byte[] bytes;
        // 处理堆缓冲区
        if (buf.hasArray()) {
            str =
                    new String(
                            buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes(), "UTF-8");
            bytes = new byte[] {};
            toHexString(bytes);
            System.out.println("堆缓冲区-------:");
            System.out.println(str);
        } else { // 处理直接缓冲区以及复合缓冲区
            bytes = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(), bytes);

            toHexString(bytes);
        }
        String regex = "(.{2})";
        return toHexString(bytes).replaceAll(regex, "$1 ").toUpperCase();
    }

    public static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1) {
            throw new IllegalArgumentException("this byteArray must not be null or empty");
        }

        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            // 0~F前面不零
            if ((byteArray[i] & 0xff) < 0x10) {
                hexString.append("0");
            }
            hexString.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return hexString.toString().toLowerCase();
    }

    public static String toHexString(float fv) {
        return Integer.toHexString(Float.floatToIntBits(fv));
    }

    public static String toHexString(long fv) {
        return Long.toHexString(fv);
    }

    public static long toDateString(String fv) {
        return Long.parseLong(fv, 16);
    }

    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date dd = df.parse("2023-09-06 15:28:03");
//        System.out.println(toHexString(594.6f));
        long dfg = toDateString("64F3DC88");
        String dd = df.format(new Date(Long.valueOf(dfg * 1000)));
        System.out.println(dd);
    }
}
