/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * @author 田平 create 2019年3月7日下午2:29:24
 */
public class CompressUtil {

	private static final String charset = "utf-8";

	public static void main(String[] args) throws Exception {
		String xx = FileUtil.getFileContent("C:\\Users\\Administrator\\Desktop\\msg.txt");
		System.out.println(xx.getBytes().length);
		String compressXX = compress(xx, 6);
		System.out.println(compressXX.length());
		String compressXX1 = new String(compress(xx.getBytes(StandardCharsets.UTF_8), 6), StandardCharsets.UTF_8);
		System.out.println(compressXX1.length());
		Date start = new Date();
		for (int i = 0; i < 10000; i++) {
			compress(xx, 6);
		}
		System.out.println(DateUtil.getUseTime(start)+" ms!");
	}

	public static byte[] compress(byte[] source, int level) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		Deflater compressor = new Deflater(level);
		try {
			compressor.setInput(source);
			compressor.finish();
			final byte[] buf = new byte[2048];
			while (!compressor.finished()) {
				int count = compressor.deflate(buf);
				bos.write(buf, 0, count);
			}
		} finally {
			compressor.end();
		}
		return bos.toByteArray();
	}

	public static byte[] uncompress(byte[] source) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		Inflater decompressor = new Inflater();
		try {
			decompressor.setInput(source);
			final byte[] buf = new byte[2048];
			while (!decompressor.finished()) {
				int count;
				try {
					count = decompressor.inflate(buf);
				} catch (Exception e) {
					throw new RuntimeException("decompressor.inflate error!", e);
				}
				bos.write(buf, 0, count);
			}
		} finally {
			decompressor.end();
		}
		return bos.toByteArray();
	}

	public static String compress(String source) {
		return compress(source, 2);
	}

	/**
	 * @param source
	 * @param level  0-9 压缩比，值越高，压缩比越大，速度越慢
	 * @return
	 */
	public static String compress(String source, int level) {
		byte[] input;
		String output;
		try {
			input = source.getBytes(charset);
			output = new String(Base64.getUrlEncoder().encode(compress(input, level)), charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("String UnsupportedEncoding error", e);
		}
		return output;
	}

	public static String uncompress(String source) {
		String output;
		try {
			byte[] input = Base64.getUrlDecoder().decode(source.getBytes(charset));
			output = new String(uncompress(input), charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("String UnsupportedEncoding error", e);
		}
		return output;
	}
}
