package org.ow2.jonas.ws.axis2.util;


import java.io.IOException;

import javax.wsdl.xml.WSDLLocator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.InputSource;

public class SimpleWSDLLocator implements WSDLLocator {

    private static final Log LOG = LogFactory.getLog(SimpleWSDLLocator.class);

    private String baseURI;
    private String lastImportLocation;
    private SimpleURIResolver resolver;

    public SimpleWSDLLocator(final String baseURI) {
        this.baseURI = baseURI;
        this.resolver = new SimpleURIResolver();
    }

    public InputSource getBaseInputSource() {
        return resolve("", this.baseURI);
    }

    public String getBaseURI() {
        return this.baseURI;
    }

    public InputSource getImportInputSource(final String parentLocation, final String importLocation) {
        return resolve(parentLocation, importLocation);
    }

    protected InputSource resolve(final String parentLocation, final String importLocation) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resolving '" + importLocation + "' relative to '" + parentLocation + "'");
        }
        try {
            this.resolver.resolve(parentLocation, importLocation);
            if (this.resolver.isResolved()) {
                this.lastImportLocation = this.resolver.getURI().toString();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Resolved location '" + this.lastImportLocation + "'");
                }
                return new InputSource(this.resolver.getInputStream());
            }
        } catch (IOException e) {
            // ignore
        }
        return null;
    }

    public String getLatestImportURI() {
        return this.lastImportLocation;
    }

    public void close() {
    }


}
