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.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.maven.linkcheck.validation.LinkValidationItem;
import org.apache.maven.linkcheck.validation.LinkValidationResult;
import org.apache.maven.linkcheck.validation.LinkValidatorManager;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.DOMReader;
import org.w3c.tidy.Tidy;

/**
 * @author <a href="mailto:bwalding@apache.org">Ben Walding</a>
 * @version $Id$
 */
public class FileToCheck
{
    /**
     * Log for debug output
     */
    private static Log LOG = LogFactory.getLog(FileToCheck.class);

    private String base;
    private File fileToCheck;
    private String status = STATUS_OK;
    private String message = "";
    private int successful;
    private int unsuccessful;
    private List links = new LinkedList();

    public static final String STATUS_UNKNOWN = null;
    public static final String STATUS_JTIDY_FAILURE = "Unable to tidy source";
    public static final String STATUS_OK = "OK";

    public FileToCheck(File baseFile, File fileToCheck)
    {
        this.base = baseFile.getAbsolutePath();
        this.fileToCheck = fileToCheck;

    }

    private void addResult(LinkCheckResult lcr)
    {
        this.links.add(lcr);
    }

    public void check(LinkValidatorManager lvm) throws Exception
    {
        successful = 0;
        unsuccessful = 0;
        status = STATUS_OK;
        message = "";

        try
        {
            final Set hrefs;
            try
            {
                hrefs = getLinks();
            }
            catch (Throwable e)
            {
                //We catch Throwable, because there is a chance that the domReader will throw
                //a stack overflow exception for some files
                LOG.info("Caught " + e.toString() + " processing " + getName());
                LOG.info("Exception Message: " + e.getLocalizedMessage());
                LinkCheckResult lcr = new LinkCheckResult();
                lcr.setStatus("PARSE FAILURE");
                lcr.setTarget("N/A");
                addResult(lcr);
                return;
            }

            for (Iterator iter = hrefs.iterator(); iter.hasNext(); )
            {
                String href = (String) iter.next();

                LOG.debug("Link Found: " + href);

                LinkCheckResult lcr = new LinkCheckResult();

                LinkValidationItem lvi = new LinkValidationItem(fileToCheck, href);
                LinkValidationResult result = lvm.validateLink(lvi);
                lcr.setTarget(href);

                switch (result.getStatus())
                {
                    case LinkValidationResult.VALID :
                        successful++;
                        lcr.setStatus("OK");
                        addResult(lcr); //At some point we won't want to store valid links.  The tests require that we do at present
                        break;
                    case LinkValidationResult.UNKNOWN :
                        unsuccessful++;
                        lcr.setStatus("UNKNOWN REF");
                        addResult(lcr);
                        break;
                    case LinkValidationResult.INVALID :
                        unsuccessful++;
                        lcr.setStatus("NOT FOUND");
                        addResult(lcr);
                        break;
                }

            }
        }
        catch (Exception e)
        {
            System.err.println(message);
            throw (e);
        }
    }

    private Set getLinks() throws FileNotFoundException
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintWriter errOut = new PrintWriter(baos);
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileToCheck));
        try
        {
            Tidy tidy = getTidy();
            tidy.setErrout(errOut);
            LOG.debug("Processing:" + fileToCheck);
            org.w3c.dom.Document domDocument = tidy.parseDOM(bin, null);

            // now read a dom4j document from
            // JTidy's W3C DOM object
            final DOMReader domReader = new DOMReader();
            final Document doc = domReader.read(domDocument);

            LOG.debug(baos.toString());

            return findUniqueLinks(doc);
        }
        finally
        {
            close(bin);
            close(baos);
        }
    }

    private void close(InputStream is)
    {
        try
        {
            is.close();
        }
        catch (Exception e)
        {
            //Don't really care.
        }
    }

    private void close(OutputStream os)
    {
        try
        {
            os.close();
        }
        catch (Exception e)
        {
            //Don't really care.
        }
    }

    private Set findUniqueLinks(Document doc)
    {
        List xpathResults = new LinkedList();

        xpathResults.addAll(doc.selectNodes("//a/@href"));
        xpathResults.addAll(doc.selectNodes("//img/@src"));

        //<link rel="stylesheet" href="...">
        xpathResults.addAll(doc.selectNodes("//link/@href"));

        //<script src="http://ar.atwola.com/file/adsWrapper.js">
        xpathResults.addAll(doc.selectNodes("//script/@src"));

        Set results = new TreeSet();
        Iterator linkIter = xpathResults.iterator();
        while (linkIter.hasNext())
        {
            Node node = (Node) linkIter.next();
            String href = node.getText();
            results.add(href);
        }

        return results;
    }

    private Tidy getTidy()
    {
        Tidy tidy = new Tidy();
        tidy.setMakeClean(true);
        tidy.setXmlTags(true);
        tidy.setXmlOut(true);
        tidy.setXHTML(true);
        tidy.setQuiet(true);
        tidy.setShowWarnings(false);
        return tidy;
    }

    /**
     * Returns the message.
     * @return String
     */
    public String getMessage()
    {
        return message;
    }

    /**
     * Returns the status.
     * @return int
     */
    public String getStatus()
    {
        return status;
    }

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

    public List getResults()
    {
        return links;
    }

    /**
     * Returns the successful.
     * @return int
     */
    public int getSuccessful()
    {
        return successful;
    }

    /**
     * Returns the unsuccessful.
     * @return int
     */
    public int getUnsuccessful()
    {
        return unsuccessful;
    }

    public String getName()
    {
        String fileName = fileToCheck.getAbsolutePath();
        if (fileName.startsWith(base)) {
            fileName = fileName.substring(base.length() + 1);
        }

        fileName = fileName.replace('\\', '/');
        return fileName;
    }

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

        buf.append("  <file>\n");
        buf.append("    <name><![CDATA[" + getName() + "]]></name>\n");
        buf.append("    <successful>" + getSuccessful() + "</successful>\n");
        buf.append("    <unsuccessful>" + getUnsuccessful() + "</unsuccessful>\n");

        Iterator iter = getResults().iterator();
        while (iter.hasNext())
        {
            LinkCheckResult result = (LinkCheckResult) iter.next();
            buf.append(result.toXML());
        }

        buf.append("  </file>\n");

        return buf.toString();
    }

}