package de.renew.export.ant;

//import de.renew.ant.AntTaskLogAppender;
import java.io.File;
import java.util.Iterator;
import java.util.Vector;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

import CH.ifa.draw.io.DrawingFileHelper;
import CH.ifa.draw.io.StatusDisplayer;
import de.renew.draw.storables.ontology.Drawing;
import de.renew.ioontology.ExtensionFileFilter;
import de.renew.ioontology.FileFilter;
import de.renew.ioontology.exporting.ExportFormat;


public abstract class AbstractExportTask extends Task {
    private final ExportFormat<Drawing> _exportFormat;
    private final String _defaultExtension;
    private File _destdir = null;
    private Vector<FileSet> _filesets = new Vector<FileSet>();

    protected AbstractExportTask(ExportFormat exportFormat) {
        super();
        this._exportFormat = exportFormat;
        FileFilter fileFilter = exportFormat.fileFilter();
        if (fileFilter instanceof ExtensionFileFilter) {
            this._defaultExtension = ((ExtensionFileFilter) fileFilter).getExtension();
        } else {
            // FIXME this is an ugly fallback (may contain capitalization and whitespace).
            this._defaultExtension = exportFormat.formatName();
        }
    }

    /**
     * Configures the root directory of the directory tree where all
     * <code>.eps</code> files are put into.
     *
     * @param dest a directory location
     **/
    public void setDestdir(File dest) {
        this._destdir = dest;
    }

    /**
     * Is invoked by the ant task and exports
     * all the given <code>.rnw</code> to <code>.eps</code> files
     * into the same directory as the original file is in.
     **/
    @Override
    public void execute() throws BuildException {
        super.execute();

        // minimal Renew logging configuration that forwards messages
        // to the Ant logging system
        Logger logger = Logger.getLogger("CH.ifa.draw");
        //AntTaskLogAppender appender = AntTaskLogAppender.getInstance(this);
        //logger.addAppender(appender);
        logger.setLevel(Level.INFO);
        logger = Logger.getLogger("de.renew");
        //logger.addAppender(appender);
        logger.setLevel(Level.INFO);


        // get all files - out of the vector full of filesets -> 2 loops
        Iterator<FileSet> filesetIterator = _filesets.iterator();
        while (filesetIterator.hasNext()) {
            FileSet elementFileSet = filesetIterator.next();
            DirectoryScanner dirScan = elementFileSet.getDirectoryScanner(getProject());
            String[] fileNames = dirScan.getIncludedFiles();
            log("filenames: " + fileNames.length, Project.MSG_VERBOSE);

            for (int i = 0; i < fileNames.length; i++) {
                String fileName = fileNames[i];
                File inFile = new File(dirScan.getBasedir() + "/" + fileName);
                log("File: " + inFile.getAbsolutePath(), Project.MSG_VERBOSE);

                // get drawing from file
                Drawing netDrawing = DrawingFileHelper.loadDrawing(inFile, new StatusDisplayer() {
                    public void showStatus(String message) {
                        log(message);
                    }
                }); //rnw-Object
                log("Drawing: " + netDrawing, Project.MSG_VERBOSE);

                if (netDrawing == null) {
                    throw new BuildException("Could not read drawing file: " + inFile);
                }

                // Export netDrawing
                try {
                    File helpFile = new File(_destdir + "/" + fileName); // helps to get the right directory path
                    File outFile = new File(
                        helpFile.getParent() + "/" + netDrawing.getName() + "."
                            + _defaultExtension);

                    //create directories
                    outFile.getParentFile().mkdirs();
                    _exportFormat.export(netDrawing, outFile);
                } catch (Exception e) {
                    throw new BuildException(e);
                }
            }
        }
    }

    public void addFileset(FileSet fileset) {
        _filesets.add(fileset);
    }
}