package eu.dnetlib.data.collector.plugins.archive.zip;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ZipIterator implements Iterator<String> {

	/** The Constant log. */
	private static final Log log = LogFactory.getLog(ZipIterator.class);

	ZipFile zipFile;
	Enumeration<? extends ZipEntry> entries;
	private String current;

	public ZipIterator(final String zipPath) {
		try {
			this.zipFile = new ZipFile(zipPath);
			this.entries = zipFile.entries();
			this.current = findNext();
		} catch (IOException e) {
			log.error("Problems opening the .zip file " + zipPath, e);
		}
	}

	public ZipIterator(final File file) {
		try {
			this.zipFile = new ZipFile(file);
			this.entries = zipFile.entries();
			this.current = findNext();
		} catch (IOException e) {
			log.error("Problems opening the .zip file " + zipFile.getName(), e);
		}
	}

	@Override
	public boolean hasNext() {
		return current != null;
	}

	@Override
	public String next() {
		String ret = new String(current);
		current = findNext();
		return ret;
	}

	@Override
	public void remove() {}

	private synchronized String findNext() {
		ZipEntry entry = null;
		while (entries.hasMoreElements() && (entry = entries.nextElement()).isDirectory()) {
			log.debug("Skipping Zip entry " + entry.getName());
		}

		if (entry == null) {
			return null;
		} else {
			log.debug("Extracting " + entry.getName());
			try {
				InputStream stream = zipFile.getInputStream(entry);
				return IOUtils.toString(stream);
			} catch (IOException e) {
				log.error("Problems extracting entry " + entry.getName(), e);
				return null;
			}
		}

	}

}
