/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.templating;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;

/**
 * An implementation of the URIResolver interface that keeps track of
 * all the URLs that have been loaded. If you set this as the URI
 * resolver for a Transformer then this will track all the
 * <code>xsl:import</code> and <code>xsl:include</code> statements.
 */
final class SimpleURIResolver implements URIResolver {
    public static final String versionId =
        "$Id: //core-platform/dev/src/com/arsdigita/templating/SimpleURIResolver.java#8 $" +
        "$Author: dennis $" +
        "$DateTime: 2004/04/07 16:07:11 $";

    private static final Logger s_log = Logger.getLogger
        (SimpleURIResolver.class);

    private final Set m_uniqueStylesheetURIs;
    private final List m_stylesheetURIs;

    public SimpleURIResolver() {
        m_uniqueStylesheetURIs = new HashSet();
        m_stylesheetURIs = new ArrayList();
    }

    /**
     * Returns all the stylesheet URIs encountered so far.
     *
     * @return a Set whose elements are isntances of java.net.URL
     */
    public List getStylesheetURIs() {
        return m_stylesheetURIs;
    }

    /**
     * Resolves a URL and returns a stream source.
     *
     * @param href the url to resolve
     * @param base the base url to resolve relative to
     */
    public Source resolve(final String href, final String base)
            throws TransformerException {
        if (s_log.isDebugEnabled()) {
            s_log.debug("Resolve " + href + " (" + base + ")");
        }

        URL baseURL = null;

        if (base != null) {
            try {
                baseURL = new URL(base);
            } catch (MalformedURLException ex) {
                throw new TransformerException("cannot parse href " + base, ex);
            }
        }

        URL thisURL = null;

        try {
            if (baseURL == null) {
                thisURL = new URL(href);
            } else {
                thisURL = new URL(baseURL, href);
            }

            if (!m_uniqueStylesheetURIs.contains(thisURL)) {
                m_uniqueStylesheetURIs.add(thisURL);
                m_stylesheetURIs.add(thisURL);
            }
        } catch (MalformedURLException ex) {
            throw new TransformerException("cannot parse href " + href, ex);
        }

        try {
            if (s_log.isDebugEnabled()) {
                s_log.debug("Got url " + thisURL);
            }

            // Optimize calls to resource servlet into file:///
            // where possible
            URL xfrmedURL = Templating.transformURL(thisURL);

            if ( xfrmedURL == null ) {
                throw new TransformerException
                    ("URL does not exist: " + thisURL);
            }

            if (s_log.isInfoEnabled()) {
                s_log.info("Loading URL " + xfrmedURL);
            }

            InputStream is = xfrmedURL.openStream();

            // NB, don't pass through 'xfrmedURL' since imports
            // are relative to 'thisURL'
            return new StreamSource(is, thisURL.toString());
        } catch (IOException ex) {
            throw new TransformerException("cannot read stream", ex);
        }
    }
}
