package tasks.bench;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Zips the project in another directory
 * 
 * @author Lisa Nguyen Quang Do
 */

public class Zip {

	private final String targetDir;
	private final String zipFileName;
	private final File projectDir;
	private final List<String> fileList;

	public Zip(String targetDir, File projectDir, String zipFileName) {
		this.projectDir = projectDir;
		this.zipFileName = zipFileName;
		this.targetDir = targetDir;
		this.fileList = new ArrayList<String>();
	}

	public File zipIt() {
		File zip = new File(targetDir + File.separator + zipFileName);
		if (zip.exists())
			return zip;

		generateFileList(projectDir);

		String zipFile = targetDir + File.separator + zipFileName;
		byte[] buffer = new byte[1024];
		try {
			FileOutputStream fos = new FileOutputStream(zipFile);
			ZipOutputStream zos = new ZipOutputStream(fos);

			for (String file : this.fileList) {
				System.out.println("File Added : " + file);
				ZipEntry ze = new ZipEntry(file);
				zos.putNextEntry(ze);
				FileInputStream in = new FileInputStream(projectDir.getAbsolutePath() + File.separator + file);
				int len;
				while ((len = in.read(buffer)) > 0)
					zos.write(buffer, 0, len);
				in.close();
			}
			zos.closeEntry();
			zos.close();

			File archive = new File(targetDir + File.separator + zipFileName);
			if (archive.exists())
				return archive;

		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	public void generateFileList(File node) {
		if (node.isFile()) {
			fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
		}
		if (node.isDirectory()) {
			String[] subNote = node.list();
			for (String filename : subNote)
				generateFileList(new File(node, filename));
		}
	}

	private String generateZipEntry(String file) {
		return file.substring(projectDir.getAbsolutePath().length() + 1, file.length());
	}
}
