package org.apache.maven.linkcheck;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2003 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.FileOutputStream;
import java.io.FilenameFilter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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>
 * @version $Id: LinkCheck.java,v 1.9 2003/04/17 12:58:33 bwalding Exp $
 */
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
     */
    List filesToCheck = null; //of FileToCheck
    public void doExecute() throws Exception
    {
        
        
        if (output == null)
        {
            throw new NullPointerException("output must be set");
        }
        LinkValidatorManager lvm = getLinkValidatorManager();

        filesToCheck = new ArrayList();
        lvm.loadCache(cache);
        List files = new ArrayList();
        findFiles(files, baseDir);
        Iterator fileIter = files.iterator();
        while (fileIter.hasNext())
        {
            FileToCheck flc = (FileToCheck) fileIter.next();
            try
            {
                filesToCheck.add(flc);
                flc.check(lvm);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        createDocument(files);
        lvm.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
                {
                    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();
            lvm.setExclude(exclude);
            lvm.addLinkValidator(new FileLinkValidator());
            MavenJellyContext ctx;
            if (getProject() == null) {
                LOG.error("maven-linkcheck-plugin: No project set.");
                ctx = new MavenJellyContext();
            } else {
                //System.out.println("Project set:" + getProject());
                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.
     * @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;
    }

}