/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
package com.netdecisions.util.ant.taskdefs;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Java;
import org.apache.tools.ant.taskdefs.MatchingTask;
import org.apache.tools.ant.types.Path;

import java.io.File;
import java.io.IOException;

import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;

public class JspC extends MatchingTask
{
    private static String lSep = System.getProperty("line.separator");

    private File urirootDir;
    private File destDir;
    private Path compileClasspath;

    protected Vector compileList = new Vector();

    public void setUriroot(File urirootDir)
    {
        this.urirootDir = urirootDir;
    }

    public void setDestdir(File destDir)
    {
        this.destDir = destDir;
    }

    public void setClasspath(Path classpath)
    {
        if (compileClasspath == null)
        {
            compileClasspath = classpath;
        }
        else
        {
            compileClasspath.append(classpath);
        }
    }

    public Path createClasspath()
    {
        if (compileClasspath == null)
        {
            compileClasspath = new Path(project);
        }

        return compileClasspath.createPath();
    }

    public void execute()
        throws BuildException
    {
        if (urirootDir == null)
        {
            throw new BuildException("Error: uriroot attribute must be set!", location);
        }
        else if (!urirootDir.isDirectory())
        {
            throw new BuildException("Error: uriroot directory is not valid!", location);
        }

        if (destDir == null)
        {
            throw new BuildException("Error: destdir attribute must be set!", location);
        }
        else if (!destDir.isDirectory())
        {
            throw new BuildException("Error: destdir directory is not valid!", location);
        }

        DirectoryScanner scanner = super.getDirectoryScanner(urirootDir);
        String allFiles[] = scanner.getIncludedFiles();

        compileList.removeAllElements();
        scanDir(urirootDir, destDir, allFiles);

        String compiler = project.getProperty("jsp.compiler");

        if (compiler == null)
        {
            compiler = "jasper.jspc";
        }

        if (compileList.size() > 0)
        {
            log("Compiling " + compileList.size()
                + " source files to " + destDir);

            if (compiler.equalsIgnoreCase("jasper.jspc"))
            {
                doJasperCompile();
            }
            else if (compiler.equalsIgnoreCase("weblogic.jspc"))
            {
                doWebLogicCompile();
            }
            else
            {
                String msg = "Don't know how to use compiler " + compiler;
                throw new BuildException(msg);
            }
        }
    }


    /**
     * Scans the directory looking for source files to be compiled.
     * The results are returned in the class variable compileList
     */
    protected void scanDir(File srcDir, File destDir, String[] files)
    {
        long now = System.currentTimeMillis();

        for (int c = 0; c < files.length; c++)
        {
            File aFile = new File(srcDir, files[c]);

            // for each JSP file
            if (aFile.getName().endsWith(".jsp"))
            {
                // get the path within the uriroot
                String fileDirString = aFile.getParent();
                String rootDirString = urirootDir.getAbsolutePath();

                int diff = fileDirString.compareTo(rootDirString);
                String destSubDir = fileDirString.substring(fileDirString.length() - diff, fileDirString.length());

                File fileDir = new File(destDir.getAbsolutePath() + destSubDir);

                String javaName = aFile.getName().substring(0, aFile.getName().indexOf(".jsp")) + ".java";
                javaName = replaceString(javaName, "_", "_0005f");

                File classFile = new File(fileDir, javaName);

                // check if the file has been modified in the future, error?
                if (aFile.lastModified() > now)
                {
                    log("Warning: file modified in the future: "
                        + aFile.getName(), Project.MSG_WARN);
                }

                if (!classFile.exists()
                    || aFile.lastModified() > classFile.lastModified())
                {
                    if (!classFile.exists())
                    {
                        log("Compiling " + aFile.getPath() + " because class file "
                            + classFile.getPath() + " does not exist", Project.MSG_VERBOSE);
                    }
                    else
                    {
                        log("Compiling " + aFile.getPath()
                            + " because it is out of date with respect to "
                            + classFile.getPath(), Project.MSG_VERBOSE);
                    }

                    compileList.addElement(aFile.getAbsolutePath());
                    //compileList.addElement(files[c]);
                }
            }
        }
    }

    private void doJasperCompile()
        throws BuildException
    {
        final String SPACE = " ";

        log("Using jasper.jspc compiler", Project.MSG_VERBOSE);

        Java javaTask = (Java)project.createTask("java");

        javaTask.setFork(true);
        javaTask.setClassname("org.apache.jasper.JspC");
        javaTask.setTaskName(super.getTaskName());

        javaTask.setClasspath(compileClasspath);

        StringBuffer argsBuffer = new StringBuffer();

        argsBuffer.append("-uriroot");
        argsBuffer.append(SPACE);
        argsBuffer.append(urirootDir.getAbsolutePath());
        argsBuffer.append(SPACE);
        argsBuffer.append("-q");
        argsBuffer.append(SPACE);
        argsBuffer.append("-d");
        argsBuffer.append(SPACE);
        argsBuffer.append(destDir.getAbsolutePath());
        argsBuffer.append(SPACE);
        argsBuffer.append("-die");
        argsBuffer.append(SPACE);

        // setup general args
        // uriroot
        // quiet by default ?
        // change output dir
        // class name ?
        // package name ?

        // loop through all of the files and execute the Java task for each file
        for (Enumeration e = compileList.elements(); e.hasMoreElements(); )
        {
            String aFileName = (String)e.nextElement();
            argsBuffer.append(aFileName);

            // add the file name to the args..
            javaTask.clearArgs();
            javaTask.createArg().setLine(argsBuffer.toString());

            if (javaTask.executeJava() != 0)
            {
                log("Warning: " + aFileName + " failed to compile", Project.MSG_WARN);
            }

            int start = argsBuffer.toString().indexOf(aFileName);
            int end = start + aFileName.length();
            argsBuffer.delete(start, end);
        }
    }

    private void doWebLogicCompile()
        throws BuildException
    {
        log("Using weblogic.jspc compiler", Project.MSG_VERBOSE);
    }

    protected String replaceString(String inpString,String escapeChars,String replaceChars)
    {
        String localString="";
        int numTokens=0;
        StringTokenizer st=new StringTokenizer(inpString,escapeChars,true);
        numTokens=st.countTokens();
        for(int i=0;i<numTokens;i++)
        {
            String test=st.nextToken();
            test=(test.equals(escapeChars)?replaceChars:test);
            localString+=test;
        }
        return localString;
    }
}