import java.io.File;
import java.util.Map;
import com.xmlmind.util.FileUtil;
import com.xmlmind.util.Zip;
import com.xmlmind.util.Console;
import com.xmlmind.util.ProgressMonitor;
import com.xmlmind.w2x.processor.CanceledException;
import com.xmlmind.w2x.processor.ProcessStep;

/**
 * Custom conversion step archiving in a ZIP file all the files found
 * in the parent directory of the file passed in <code>state[0]</code>.
 * <p>Implementation of <tt>sample_plugins/wh5_zip/zip_step.jar</tt>.
 */
public class ZipStep extends ProcessStep {
    public ZipStep(String stepName) {
        super(stepName);
    }

    public void process(Object[] state, Map<String,String> parameters,
                        int[] stepCounter, ProgressMonitor monitor)
        throws Exception {
        boolean includeTopDir = 
            getBooleanParameter(parameters, "include-top-dir", true);

        File zipFile = getFileParameter(parameters, "out-file", null);
        if (zipFile == null) {
            missingParameter("out-file");
        }
        
        if (!(state[0] instanceof File)) {
            illegalState(File.class);
        }
        File srcDir = ((File) state[0]).getParentFile();

        if (srcDir == null ||
            !srcDir.isDirectory() || 
            !srcDir.equals(FileUtil.setExtension(zipFile, null))) {
            throw new RuntimeException("internal error: '" + srcDir + 
                                       "', not the expected source directory");
        }

        progress("Archiving '" + srcDir + "' to '" + zipFile + "'...", 
                 stepCounter, monitor);
        debugParameters(parameters, monitor);

        Zip.zip(srcDir, includeTopDir, /*filter*/ null, zipFile);

        if (!monitor.message("Deleting '" + srcDir + "'...",
                             Console.MessageType.DEBUG)) {
            throw new CanceledException();
        }
        FileUtil.deleteDir(srcDir);

        state[0] = zipFile;
    }
}
