package org.apache.slide.projector.processor.xml;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.contract.Context;
import org.apache.commons.contract.descriptor.ParameterDescriptor;
import org.apache.commons.contract.descriptor.ResultEntryDescriptor;
import org.apache.commons.contract.i18n.ParameterMessage;
import org.apache.commons.i18n.LocalizedError;
import org.apache.commons.i18n.LocalizedMessage;
import org.apache.slide.projector.constraints.XMLConstraints;
import org.apache.slide.projector.processor.ConfigurableProcessor;
import org.apache.slide.projector.processor.ConfigurationException;
import org.apache.slide.projector.processor.SimpleProcessor;
import org.apache.slide.projector.repository.RepositoryException;
import org.apache.slide.projector.value.DocumentValue;
import org.apache.slide.projector.value.Streamable;
import org.jdom.Document;
import org.jdom.transform.JDOMResult;
import org.jdom.transform.JDOMSource;

/**
 * @version $Revision: 1.5 $
 */

public class XSLTransformer extends SimpleProcessor implements ConfigurableProcessor {
    private Transformer transformer;

    public Object process(Object input, Context context) throws Exception {
    	Document document = ((DocumentValue)input).getDocument();
        JDOMResult result = new JDOMResult();
        transformer.transform(new JDOMSource(document), result);
        return new DocumentValue(result.getDocument());
    }

    public ParameterDescriptor getParameterDescriptor() {
        return new ParameterDescriptor(INPUT, new ParameterMessage("xslTransformer/parameter/input"), new XMLConstraints());
    }

    public ResultEntryDescriptor getResultEntryDescriptor() {
        return new ResultEntryDescriptor(OUTPUT, new LocalizedMessage("xslTransformer/result/output"), XMLConstraints.UNCONSTRAINED);
    }

    public void configure(Streamable config) throws ConfigurationException {
        try {
            transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(config.getInputStream()));
        } catch (TransformerConfigurationException e) {
            throw new ConfigurationException(new LocalizedError("xslTransformer/creationgFailed"), e);
        } catch (RepositoryException e) {
            throw new ConfigurationException(new LocalizedError("xslTransformer/creationgFailed"), e);
        }
    }
}