package org.apache.maven.jxr;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 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 acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache Maven" 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",
 *    "Apache Maven", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * 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/>.
 */

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.jxr.pacman.PackageManager;
import org.apache.tools.ant.DirectoryScanner;

/**
 * Main entry point into Maven used to kick off the XReference code building.
 *
 * @author <a href="mailto:burton@apache.org">Kevin A. Burton</a>
 * @version $Id: JXR.java,v 1.6 2003/08/19 04:45:06 dion Exp $
 */
public class JXR
{
    /** Log. */
    private static final Log log = LogFactory.getLog(JxrBean.class);

    /**
     * Description of the Field
     */
    public final static String NOTICE =
        "This page was automatically generated by " + 
        "<a href=\"http://maven.apache.org/\">Maven</a>";

    /**
     * Path to all source.files
     */
    private String source = "";

    /**
     * Path to destination
     */
    private String dest = "";

    /**
     * Relative path to javadocs, suitable for hyperlinking
     */
    private String javadocLinkDir;
    
    /**
     * Handles taking .java files and changing them into html. "More than meets
     * the eye!" :)
     */
    private CodeTransform transformer;

    /**
     * The revision of the module currently being processed.
     */
    private String revision;

    /**
     * The constructor for the JXR class.
     *
     * @param packageManager The Package Manager for this project
     * @param revision The CVS revision of this file.
     * @param source The directory that files are being read from (src/java)
     * @param source
     * @param dest
     */
    public JXR(PackageManager packageManager,
               String source,
               String dest,
               String javadocLinkDir,
               String revision)
    {
        this.transformer = new CodeTransform(packageManager);
        this.source = source;
        this.dest = dest;
        this.javadocLinkDir = javadocLinkDir;
        this.revision = revision;

        this.process();
    }


    /**
     * Now that we have instantiated everythign. Process this JXR task.
     */
    private void process()
    {

        DirectoryScanner ds = new DirectoryScanner();

        ds.addDefaultExcludes();

        File dir = new File(this.getSource());

        if (!dir.exists())
        {
            if (dir.mkdirs() == false)
            {
                throw new IllegalStateException(
                    "Your source directory does not exist and could not be created:" +
                    this.getSource());
            }
        }

        ds.setBasedir(this.getSource());
        ds.scan();

        //now get the list of included files

        String[] files = ds.getIncludedFiles();

        for (int i = 0; i < files.length; ++i)
        {
            if (!updated(files[i]))
            {
                String source = this.getSource() + 
                    System.getProperty("file.separator") + files[i];

                try
                {

                    if (isJavaFile(source))
                    {
                        transform(source, getDestination(source));
                    }

                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Check to see if the file is a Java source file
     *
     * @param filename The name of the file to check
     * @return <code>true
     *    </true>
     *    if the file is a Java file
     */
    public static boolean isJavaFile(String filename)
    {
        return filename.endsWith(".java");
    }

    /**
     * Check to see if the file is a HTML file
     *
     * @param filename The name of the file to check
     * @return <code>true
     *    </true>
     *    if the file is a HTML file
     */
    public static boolean isHtmlFile(String filename)
    {
        return filename.endsWith(".html");
    }

    /**
     * Given a filename get the destination on the filesystem of where to store
     * the to be generated HTML file. Pay attention to the package name.
     *
     * @param filename The name of the file to find
     * @return A String with the store destination.
     */
    private String getDestination(String filename)
    {

        String dest = new String(filename);

        //remove the source directory from the filename.

        dest = dest.substring(this.getSource().length(), dest.length());

        int start = 0;
        int end = dest.indexOf(".java");

        if (end != -1)
        {
            //remove the .java from the filename
            dest = dest.substring(start, end);
        }

        //add the destination directory to the filename.
        dest = this.getDest() + dest;

        //add .html to the filename

        dest = dest + ".html";

        return dest;
    }

    /**
     * Given a source file transform it into HTML and write it to the
     * destination (dest) file.
     *
     * @param source The jave source file
     * @param dest The directory to put the HTML into
     * @throws IOException Thrown if the transform can't happen for some reason.
     */
    private void transform(String source, String dest)
        throws IOException
    {

        log.debug(source + " -> " + dest);

        transformer.transform(source, dest, javadocLinkDir, this.revision);

    }

    /**
     * <p>
     *
     * Given a java source file determine if this needs updating. This is
     * determined by:</p>
     * <ul>
     *   <li> The class doesn't exist in the destination directory</li>
     *   <li> The file does exist in the destination directory but is older</li>
     *
     * </ul>
     *
     */
    private boolean updated(String file)
    {
        return false;
    }

    /**
     * Get the path to the source files
     *
     * @return The path to the source files
     */
    public String getSource()
    {
        return this.source;
    }

    /**
     * Get the path to the destination files
     *
     * @return The path to the destination files
     */
    public String getDest()
    {
        return this.dest;
    }

}

