package org.apache.maven.linkcheck.validation;

/* ====================================================================
 *   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 org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Checks links which are normal URLs
 * @author <a href="mailto:bwalding@apache.org">Ben Walding</a>
 * @version $Id$
 */
public class HTTPLinkValidator implements LinkValidator
{
    /**
     * Log for debug output
     */
    private static Log LOG = LogFactory.getLog(HTTPLinkValidator.class);

    private static final LinkValidationResult LVR_INVALID =
        new LinkValidationResult(LinkValidationResult.INVALID, true);

    private static final LinkValidationResult LVR_VALID = new LinkValidationResult(LinkValidationResult.VALID, true);

    private String proxyHost;
    private int proxyPort;
    private String proxyUser;
    private String proxyPass;

    public HTTPLinkValidator(String proxyHost, String proxyPort, String proxyUser, String proxyPass)
    {
        if (proxyHost == null || proxyHost.trim().equals(""))
        {
            LOG.info("maven-linkcheck-plugin: Not using a proxy");
            this.proxyHost = null;
        }
        else
        {
            this.proxyHost = proxyHost;
            try{
              this.proxyPort = Integer.parseInt(proxyPort);
            }catch(NumberFormatException e){
              LOG.warn("maven-linkcheck-plugin: Invalid number for Proxy Port:" + proxyPort);
              LOG.warn("maven-linkcheck-plugin: Proxy Port won't be used.");
              this.proxyPort = 0;
            }
            this.proxyUser = proxyUser;
            this.proxyPass = proxyPass;
            LOG.info("maven-linkcheck-plugin: Proxy Host:" + proxyHost);
            LOG.info("maven-linkcheck-plugin: Proxy Port:" + proxyPort);
            LOG.info("maven-linkcheck-plugin: Proxy User:" + proxyUser);
        }
    }

    /**
     * @see org.apache.maven.linkcheck.LinkValidator#validateLink(org.apache.maven.linkcheck.LinkValidationItem)
     */
    public LinkValidationResult validateLink(LinkValidationItem lvi)
    {
        try
        {
            String link = lvi.getLink();
            LOG.debug("Checking web link:" + link);

            HttpClient cl = new HttpClient();
            HostConfiguration hc = new HostConfiguration();

            if (proxyHost != null)
            {
                hc.setProxy(proxyHost, proxyPort);
            }
            HttpState state = new HttpState();

            if (proxyUser != null && proxyPass != null)
            {
                state.setProxyCredentials(null, null, new UsernamePasswordCredentials(proxyUser, proxyPass));
            }

            cl.setHostConfiguration(hc);
            cl.setState(state);
            
            // execute the GET
            HeadMethod hm = checkLink(cl, link);
            StatusLine sl = hm.getStatusLine();
            
            if (sl == null) {
                LOG.info("Unknown error validating link : " + link);
                return LVR_INVALID;
            }
            
            if (hm.getStatusCode() == 302)
            {
                Header locationHeader = hm.getResponseHeader("Location");
                if (locationHeader == null)  {
                    LOG.info("Site sent redirect, but did not set Location header");
                } else  {
                    String newLink = locationHeader.getValue();
                    LOG.debug("Following 1 redirect to " + newLink);
                    hm = checkLink(cl, newLink);
                }
            }

            //FIXME: This constant is defined somewhere, but I can't remember where...
            if (hm.getStatusCode() == 200)
            {
                return LVR_VALID;
            }
            else
            {
                String msg = "Received: [" + hm.getStatusCode() + "] for " + link;
                LOG.info(msg);
                System.out.println(msg);
                return LVR_INVALID;
            }

        }
        catch (Exception e)
        {
            LOG.warn("Error accessing " + lvi.getLink(), e);
            e.printStackTrace();
            return LVR_INVALID;
        }

    }

    private HeadMethod checkLink(HttpClient cl, String link)
    {   
        HeadMethod hm = new HeadMethod(link);
        try
        {
            LOG.info("Checking link " + link);
            hm.setFollowRedirects(true);
            cl.executeMethod(hm);
            LOG.debug("Checked link " + link);
        }
        catch (Exception e)
        {
            LOG.warn("Error validating " + link + ": " + e);
            LOG.debug("Exception was", e);
        }
        return hm;
    }

    /**
     * @see org.apache.maven.linkcheck.LinkValidator#getResourceKey(org.apache.maven.linkcheck.LinkValidationItem)
     */
    public Object getResourceKey(LinkValidationItem lvi)
    {
        String link = lvi.getLink();

        if (!link.startsWith("http://"))
            return null;

        int hashPos = link.indexOf("#");
        if (hashPos != -1)
            link = link.substring(0, hashPos);

        return link;
    }

}
