package eu.dnetlib.bioschemas.api.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;

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

public class CompressorUtil {

	public static String decompressValue(final String abstractCompressed) {
		try {
			byte[] byteArray = Base64.decodeBase64(abstractCompressed.getBytes());
			GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(byteArray));
			final StringWriter stringWriter = new StringWriter();
			IOUtils.copy(gis, stringWriter);
			return stringWriter.toString();
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		}
	}

    public static  String compressValue(final String value) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(value.getBytes());
        gzip.close();
        return java.util.Base64.getEncoder().encodeToString(out.toByteArray());
    }
}
