package org.example.Utils;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * ==============================================================================
 * 功能描述：GZipUtil
 * 备注：gzip压缩相关
 * ==============================================================================
 */
public class GZipUtil {

    /**
     * GZIP解压
     *
     * @param zippedData 压缩后的字节数组
     * @return 解压后的字节数组
     */
    public static byte[] decompress(byte[] zippedData) {
        if (zippedData == null || zippedData.length == 0) {
            return new byte[0];
        }

        try (ByteArrayInputStream bais = new ByteArrayInputStream(zippedData);
             GZIPInputStream gzipIn = new GZIPInputStream(bais);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

            byte[] block = new byte[1024];
            int bytesRead;
            while ((bytesRead = gzipIn.read(block)) != -1) {
                baos.write(block, 0, bytesRead);
            }
            return baos.toByteArray();

        } catch (IOException e) {
            // 捕获异常并返回空数组（与原C#逻辑一致）
            return new byte[0];
        }
    }

    /**
     * 解压并转换为字符串
     *
     * @param zippedData 压缩后的字节数组
     * @return 解压后的字符串
     */
    public static String unZip(byte[] zippedData) {
        byte[] decompressedData = decompress(zippedData);
        return new String(decompressedData, StandardCharsets.UTF_8);
    }

    /**
     * 将传入字符串以GZip算法压缩后，返回Base64编码字符
     *
     * @param rawString 需要压缩的字符串
     * @return 压缩后的Base64编码的字符串
     */
    public static String gZip(String rawString) {
        if (rawString == null || rawString.isEmpty()) {
            return "";
        }

        byte[] rawData = rawString.getBytes(StandardCharsets.UTF_8);
        byte[] zippedData = compress(rawData);
        return Base64.getEncoder().encodeToString(zippedData);
    }

    /**
     * GZip压缩
     *
     * @param rawData 原始字节数组
     * @return 压缩后的字节数组
     */
    public static byte[] compress(byte[] rawData) {
        if (rawData == null || rawData.length == 0) {
            return new byte[0];
        }

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) {

            gzipOut.write(rawData);
            gzipOut.finish(); // 确保所有数据都被写入
            return baos.toByteArray();

        } catch (IOException e) {
            // 压缩失败时返回空数组
            return new byte[0];
        }
    }
}
