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 java.io.File;

/**
 * A link validator solely for files on the local filesystem.
 * 
 * @author <a href="mailto:bwalding@apache.org">Ben Walding</a>
 * @version $Id$
 */
public class FileLinkValidator implements LinkValidator {
    private final static LinkValidationResult LVR_INVALID =
        new LinkValidationResult(LinkValidationResult.INVALID, false);
        
    private final static LinkValidationResult LVR_VALID =
        new LinkValidationResult(LinkValidationResult.VALID, false);

    /**
     * @see org.apache.maven.linkcheck.LinkValidator#validateLink(org.apache.maven.linkcheck.LinkValidationItem)
     */
    public LinkValidationResult validateLink(LinkValidationItem lvi) {
        File f = getFile(lvi);

        if (f.exists())
            return LVR_VALID;
        else
            return LVR_INVALID;
    }

    /**
     * 
     * @param lvi
     * @return File
     */
    protected File getFile(LinkValidationItem lvi) {
        String link = lvi.getLink();
        if (link.indexOf('#') != -1) {
            link = link.substring(0, link.indexOf('#'));

            //If the link was just #fred or similar, then the file is the file it came from
            //XXX: Theoretically we could even validate the anchor tag?
            if (link.trim().length() == 0)
                return lvi.getSource();
        }

        File f = new File(lvi.getSource().getParentFile(), link);
        return f;
    }

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

        if (link.indexOf(':') != -1)
            return null;

        return getFile(lvi).getAbsolutePath();
    }

}
