package org.objectweb.util.ant;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.ZipFileSet;

import java.util.List;
import java.util.ArrayList;
import java.io.File;

/**
 * Permits to specify a group of zip which only some entries must be zipped. 
 */
public class Zip extends org.apache.tools.ant.taskdefs.Zip {

	public List zipGroups;

	public Zip() {
		super();
		zipGroups = new ArrayList();
	}

	public ZipGroup createZipGroup() {
		ZipGroup g = new ZipGroup(getProject());
		zipGroups.add(g);
		return g;
	}

	/**
	 * represents a group of zip
	 */
	public class ZipGroup extends MatchingTask {
		// entries of zip files
		public ZipEntries theEntries;

		//contains zip files
		public File dir = null;

		public ZipGroup(Project p) {
			super();
			setProject(p);
			theEntries = new ZipEntries(p);
		}

		public ZipEntries createZipEntries() {
			return theEntries;
		}

		public void setDir(File dir) {
			this.dir = dir;
		}

		public String[] getZipFileNames() {
			return DirectoryScannerHelper.getSelectedFilesAsString(
			        super.getDirectoryScanner(dir), getProject());
		}

		/**
		 * used for the entries of zip files
		 */
		class ZipEntries extends MatchingTask {

			public ZipEntries(Project p) {
				super();
				setProject(p);
			}

			public DirectoryScanner getDirectoryScanner(File p) {
				return super.getDirectoryScanner(p);
			}

			public FileSet getInnerFileSet() {
				return fileset;
			}
		}
	}


	/**
	 * permit to use the constructor of ZipFileSet with the FileSet parameter
	 */
	public class MyZipFileSet extends ZipFileSet {
		public MyZipFileSet(FileSet fileset, File src) {
			super(fileset);
			setSrc(src);
		}
	}

	public void execute() throws BuildException {
		//foreach group of zip files
		for (int i = 0; i < zipGroups.size(); i++) {
			ZipGroup zg = (ZipGroup) zipGroups.get(i);
			String[] zipfiles = zg.getZipFileNames();
			// for each zip file
			for (int j = 0; j < zipfiles.length; j++) {
				//create a ZipFileSet using include/exclude for the entries
				super.addFileset(
						new MyZipFileSet(zg.theEntries.getInnerFileSet(),
								new File(zg.dir, zipfiles[j])));
			}
		}
		super.execute();
	}
}
