package com.pig4cloud.pig.statistics.socket;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 协议处理器，负责数据包的解析和构建
 */
public class ProtocolHandler {
    // 协议定义
    public static final byte PACKET_HEADER = 0x2;
    public static final byte PACKET_TAIL = 0x3;
    public static final byte TYPE_TEXT = 0x01;
    public static final byte TYPE_IMAGE = 0x02;

    /**
     * 从输入流读取一个完整的数据包
     */
    public Packet readPacket(InputStream in) throws IOException {
        ByteArrayOutputStream packetBuffer = new ByteArrayOutputStream();
        boolean inPacket = false;
        int dataType = -1;
        byte[] lengthBytes = new byte[4];
        int lengthIndex = 0;
        int contentLength = -1;
        ByteArrayOutputStream contentBuffer = new ByteArrayOutputStream();

        int b;
        while ((b = in.read()) != -1) {
            byte currentByte = (byte) b;

            // 处理包头
            if (!inPacket && currentByte == PACKET_HEADER) {
                inPacket = true;
                packetBuffer.reset();
                packetBuffer.write(currentByte);
                lengthIndex = 0;
                contentLength = -1;
                contentBuffer.reset();
                continue;
            }

            // 处理包内数据
            if (inPacket) {
                packetBuffer.write(currentByte);

                // 读取数据类型
                if (dataType == -1) {
                    dataType = currentByte & 0xFF;
                    continue;
                }

                // 读取数据长度（4字节）
                if (contentLength == -1) {
                    lengthBytes[lengthIndex++] = currentByte;
                    if (lengthIndex == 4) {
                        // 转换4字节为整数（大端模式）
                        contentLength = ((lengthBytes[0] & 0xFF) << 24) |
                                       ((lengthBytes[1] & 0xFF) << 16) |
                                       ((lengthBytes[2] & 0xFF) << 8) |
                                       (lengthBytes[3] & 0xFF);
                    }
                    continue;
                }

                // 读取数据内容
                if (contentBuffer.size() < contentLength) {
                    contentBuffer.write(currentByte);

                    // 检查是否已读取所有内容
                    if (contentBuffer.size() == contentLength) {
                        // 接下来应该是包尾
                        continue;
                    }
                } else {
                    // 检查包尾
                    if (currentByte == PACKET_TAIL) {
                        // 完整包接收完成，返回数据包
                        return new Packet(dataType, contentBuffer.toByteArray());
                    } else {
                        // 包尾不正确，视为无效包
                        System.err.println("无效的包尾，丢弃数据包");
                        inPacket = false;
                        dataType = -1;
                        contentLength = -1;
                    }
                }
            }
        }

        // 到达流末尾，返回null
        return null;
    }

    /**
     * 发送一个数据包到输出流
     */
    public void sendPacket(OutputStream out, int dataType, byte[] data) throws IOException {
        // 构造响应包
        ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();

        // 写入包头
        responseBuffer.write(PACKET_HEADER);

        // 写入数据类型
        responseBuffer.write(dataType);

        // 写入数据长度（4字节，大端模式）
        responseBuffer.write((data.length >> 24) & 0xFF);
        responseBuffer.write((data.length >> 16) & 0xFF);
        responseBuffer.write((data.length >> 8) & 0xFF);
        responseBuffer.write(data.length & 0xFF);

        // 写入数据内容
        responseBuffer.write(data);

        // 写入包尾
        responseBuffer.write(PACKET_TAIL);

        // 发送响应
        out.write(responseBuffer.toByteArray());
        out.flush();
    }
}
    