package eu.dnetlib.data.collector.plugins.archives.targz;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import junit.framework.Assert;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.junit.Ignore;
import org.junit.Test;

import eu.dnetlib.data.collector.plugins.archive.targz.TarGzIterator;

@Ignore
public class TarGzIteratorTest {

	@Ignore
	@Test
	public void test() {
		try {
			int nFiles = 14860;
			File f1 = createTarGzArchive(nFiles);
			iterate(nFiles, f1);
			// f1.delete();

			nFiles = 5971;
			File f2 = createTarGzArchive(nFiles);
			iterate(nFiles, f2);
			// f2.delete();

			nFiles = 198463;
			File f3 = createTarGzArchive(nFiles);
			iterate(nFiles, f3);
			// f3.delete();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private File createTarGzArchive(final int nFiles) throws IOException {
		final StringBuilder sb = new StringBuilder();
		sb.append("Test String");

		File targz = File.createTempFile("testTarGz", ".tar.gz");
		FileOutputStream fOut = new FileOutputStream(targz);
		BufferedOutputStream bOut = new BufferedOutputStream(fOut);
		GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(bOut);
		TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut);

		byte[] data = sb.toString().getBytes();
		for (int i = 0; i < nFiles; i++) {
			TarArchiveEntry tarEntry = new TarArchiveEntry(String.format("%d.txt", i));
			tarEntry.setSize(data.length);
			tOut.putArchiveEntry(tarEntry);

			tOut.write(data, 0, data.length);
			tOut.closeArchiveEntry();
		}

		tOut.close();
		gzOut.close();
		bOut.close();
		fOut.close();
		return targz;
	}

	private void iterate(final int nFiles, final File zipFile) {
		TarGzIterator testedIterator = new TarGzIterator(zipFile);
		int counter = 0;
		while (testedIterator.hasNext()) {
			testedIterator.next();
			counter++;
		}
		Assert.assertEquals(nFiles, counter);
	}
}
