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.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author <a href="mailto:bwalding@apache.org">Ben Walding</a>
 * @author <a href="mailto:carlos@apache.org">Carlos Sanchez</a>
 * @version $Id$
 */

public class LinkValidatorManager {
    /**
     * Log for debug output
     */
    private static Log LOG = LogFactory.getLog(LinkValidatorManager.class);

    private List validators = new LinkedList();
    private LinkValidatorCache cache = new LinkValidatorCache(this);
    private String[] excludes = new String[0];

    public LinkValidatorManager() {

    }

    public void addLinkValidator(LinkValidator lv) {
        validators.add(lv);
    }

    public List getValidators() {
        return validators;
    }

    public LinkValidationResult validateLink(LinkValidationItem lvi)
        throws Exception {
        {
            LinkValidationResult status = cache.getCachedResult(lvi);
            if (status != null) {
                return status;
            }
        }

        for (int i = 0; i < excludes.length; i++) {
            if (excludes[i] != null && lvi.getLink().startsWith(excludes[i])) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Excluded " + lvi.getLink());
                }
                return new LinkValidationResult(LinkValidationResult.VALID, false);
            }
        }

        Iterator iter = validators.iterator();
        while (iter.hasNext()) {
            LinkValidator lv = (LinkValidator) iter.next();

            Object resourceKey = lv.getResourceKey(lvi);

            if (resourceKey != null) {

                LinkValidationResult lvr = lv.validateLink(lvi);

                if (lvr.getStatus() == LinkValidationResult.NOTMINE) {
                    continue;
                }

                cache.setCachedResult(resourceKey, lvr);
                return lvr;

            }

        }

        LOG.info("Unable to validate link : " + lvi.getLink());
        return new LinkValidationResult(LinkValidationResult.UNKNOWN, false);
    }

    public void loadCache(String cacheFilename) {
        try {
            File f = new File(cacheFilename);
            if (f.exists()) {
                BufferedInputStream is = new BufferedInputStream(
                        new FileInputStream(cacheFilename)); 
                this.cache.load(is);
                is.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveCache(String cacheFilename) {
        try {
            File cacheFile = new File(cacheFilename);
            File dir = cacheFile.getParentFile();
            if (dir != null) {
                dir.mkdirs();
            }
            BufferedOutputStream os = new BufferedOutputStream(
                    new FileOutputStream(cacheFilename)); 
            this.cache.save(os);
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns the exclude.
     * @return String
     * @deprecated use getExcludes()
     */
    public String getExclude() {
        return excludes[0];
    }

    /**
     * Sets the exclude.
     * @param exclude The exclude to set
     * @deprecated use setExcludes()
     */
    public void setExclude(String exclude) {
        this.excludes = new String[] {exclude};
    }

    /**
     * Returns the excludes.
     * @return String[]
     */
    public String[] getExcludes() {
        return excludes;
    }

    /**
     * Sets the excludes.
     * @param excludes The excludes to set
     */
    public void setExcludes(String[] excludes) {
        this.excludes = excludes;
    }

}
