package com.hz.pm.api.common.util;

import cn.hutool.core.util.StrUtil;
import com.ningdatech.basic.exception.BizException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * <p>
 * gzip压缩工具类
 * </p>
 *
 * @author WendyYang
 */
public class GzipUtil {

    private GzipUtil() {
    }

    /**
     * 使用gzip进行压缩
     */
    public static String zip(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
            gzip.write(content.getBytes());
            gzip.finish();
            byte[] bytes = bos.toByteArray();
            return new BASE64Encoder().encode(bytes);
        } catch (IOException e) {
            throw new BizException(e);
        }
    }

    /**
     * 使用gzip进行解压缩
     */
    public static String unzip(String content) {
        if (StrUtil.isBlank(content)) {
            return content;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try (ByteArrayInputStream bis = new ByteArrayInputStream(decoder.decodeBuffer(content));
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
             GZIPInputStream gis = new GZIPInputStream(bis)) {
            byte[] buffer = new byte[1024 * 16];
            int offset;
            while ((offset = gis.read(buffer)) != -1) {
                bos.write(buffer, 0, offset);
            }
            return bos.toString();
        } catch (IOException e) {
            throw new BizException(e);
        }
    }

}
