package org.apache.maven.linkcheck;

/* ====================================================================
 *   Copyright 2001-2004 The Apache Software Foundation.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * ====================================================================
 */

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.jelly.MavenJellyContext;
import org.apache.maven.linkcheck.validation.FileLinkValidator;
import org.apache.maven.linkcheck.validation.HTTPLinkValidator;
import org.apache.maven.linkcheck.validation.LinkValidatorManager;
import org.apache.maven.linkcheck.validation.MailtoLinkValidator;
import org.apache.maven.project.Project;

/**
 * The main bean to be called whenever a set of documents should have
 * their links checked.
 * 
 * @author <a href="mailto:bwalding@apache.org">Ben Walding</a>
 * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a>
 * @version $Id$
 */
public class LinkCheck
{
    /** Log */
    private static final Log LOG = LogFactory.getLog(LinkCheck.class);

    /** Output file for xml document */
    private File output;

    /** Output encoding for the xml document */
    private String outputEncoding;

    private File baseDir;
    private String cache;
    private String exclude;
    private Project project;

    /**
     * Set the base directory for the change log generator.
     * @param base the base directory
     */
    public void setBasedir(File base)
    {
        this.baseDir = base;
    }

    /**
     * Get the base directory for the change log generator.
     *
     * @return the base directory
     */
    public File getBasedir()
    {
        return baseDir;
    }

    /**
     * Set the output file for the log.
     * @param output the output file
     */
    public void setOutput(File output)
    {
        this.output = output;
    }

    /**
     * Execute task.
     * @throws FileNotFoundException if {@link ChangeLog#base} doesn't exist
     * @throws IOException if there are problems running CVS
     * @throws UnsupportedEncodingException if the underlying platform doesn't
     *      support ISO-8859-1 encoding
     */
    private List filesToCheck = null; //of FileToCheck
    public void doExecute() throws Exception
    {
        if (output == null)
        {
            throw new NullPointerException("output must be set");
        }
        LinkValidatorManager validator = getLinkValidatorManager();

        filesToCheck = new LinkedList();
        validator.loadCache(cache);
        List files = new LinkedList();
        LOG.debug("Locating all files to be checked...");
        findFiles(files, baseDir);
        LOG.debug("Located all files to be checked.");
        Iterator fileIter = files.iterator();
        while (fileIter.hasNext())
        {
            FileToCheck flc = (FileToCheck) fileIter.next();
            try
            {
                filesToCheck.add(flc);
                LOG.info("Validating " + flc.getName());
                flc.check(validator);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        createDocument(files);
        validator.saveCache(cache);
    }

    public List getFiles()
    {
        return filesToCheck;
    }

    public void findFiles(List allFiles, File base)
    {
        FilenameFilter ff = new FilenameFilter()
        {
            /**
             * @see java.io.FilenameFilter#accept(java.io.File, java.lang.String)
             */
            public boolean accept(File dir, String name)
            {
                File n = new File(dir, name);
                if (n.isDirectory())
                    return true;

                if (name.endsWith(".html"))
                    return true;

                return false;
            }
        };

        File[] f = base.listFiles(ff);

        if (f != null)
        {
            for (int i = 0; i < f.length; i++)
            {
                File file = f[i];
                if (file.isDirectory())
                {
                    findFiles(allFiles, file);
                }
                else
                {
                    if (allFiles.size() % 1000 == 0) { 
                        LOG.info("Found " + allFiles.size() + " files so far.");
                        final long MEG = 1024 * 1024;
                        Runtime r = Runtime.getRuntime();
                        LOG.info( "  Memory: " + ((r.totalMemory() - r.freeMemory()) / MEG) + "M/" + (r.totalMemory() / MEG) + "M");
                    }
                    //LOG.info(" File - " + file);
                    allFiles.add(new FileToCheck(baseDir, file));
                }
            }
        }
    }

    /**
     * Create the XML document from the currently available details
     * @throws FileNotFoundException when the output file previously provided
     *      does not exist
     * @throws UnsupportedEncodingException when the platform doesn't support
     *      ISO-8859-1 encoding
     */
    private void createDocument(List files) throws Exception
    {
        File dir = output.getParentFile();
        if (dir != null)
        {
            dir.mkdirs();
        }
        PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output), getOutputEncoding()));

        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"").append(getOutputEncoding()).append("\" ?>\n");

        out.write(buffer.toString());

        out.write(toXML());
        out.close();
    }

    /**
     * Returns the outputEncoding.
     * @return String
     */
    public String getOutputEncoding()
    {
        return outputEncoding;
    }

    /**
     * Sets the outputEncoding.
     * @param outputEncoding The outputEncoding to set
     */
    public void setOutputEncoding(String outputEncoding)
    {
        this.outputEncoding = outputEncoding;
    }

    LinkValidatorManager lvm = null;
    public LinkValidatorManager getLinkValidatorManager()
    {
        if (lvm == null)
        {
            lvm = new LinkValidatorManager();
            if (exclude != null) {
                StringTokenizer st = new StringTokenizer(exclude, " ,\t\n\r\f");
                String[] tokens = new String[st.countTokens()];
                for (int i = 0; i < tokens.length; i++) {
                    tokens[i] = st.nextToken();
                }
                lvm.setExcludes(tokens);
            }
            lvm.addLinkValidator(new FileLinkValidator());
            // Project is only null in test cases
            if (getProject() != null) {
                MavenJellyContext ctx = ((Project) getProject()).getContext();
                lvm.addLinkValidator(new HTTPLinkValidator(ctx.getProxyHost(), ctx.getProxyPort(), ctx.getProxyUserName(), ctx.getProxyPassword()));
            }
                
            lvm.addLinkValidator(new MailtoLinkValidator());
            lvm.loadCache(cache);
        }
        return lvm;
    }

    /**
     * Returns the cacheFile.
     * @return String
     */
    public String getCache()
    {
        return cache;
    }

    /**
     * Sets the cacheFile.
     * @param cacheFile The cacheFile to set
     */
    public void setCache(String cache)
    {
        this.cache = cache;
    }

    /**
     * Returns the exclude.
     * @return String
     */
    public String getExclude()
    {
        return exclude;
    }

    /**
     * Sets the exclude, a string with exclude locations delimited by the space
     * character, the comma character, the tab character, the newline character,
     * the carriage-return character, and the form-feed character.
     * 
     * @param exclude
     *            The exclude to set
     */
    public void setExclude(String exclude)
    {
        this.exclude = exclude;
    }

    public String toXML()
    {
        StringBuffer buf = new StringBuffer();

        buf.append("<linkcheck>\n");

        //buf.append("  <files>\n");
        for (Iterator iter = getFiles().iterator(); iter.hasNext();)
        {
            FileToCheck ftc = (FileToCheck) iter.next();
            buf.append(ftc.toXML());
        }
        //buf.append("  </files>\n");
        buf.append("</linkcheck>\n");
        return buf.toString();
    }

    /**
     * @return Project
     */
    public Object getProject()
    {
        return project;
    }

    /**
     * Sets the project.
     * @param project The project to set
     */
    public void setProject(Object project)
    {
        //System.out.println("Setting project: " + project);
        this.project = (Project) project;
    }

}
