package sklep.rest.ext;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import javax.ws.rs.WebApplicationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.util.JAXBSource;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.xmlgraphics.util.MimeConstants;

public class ObslugaXSL {
	// obiekt -(za pomocą JAXB)-> XML -(za pomocą transformera)-> XML(XSL-FO)
	// --(za pomocą Apache FOP)-> PDF -> output
	public void wypiszPDF(Object obj, OutputStream output) {
		try(InputStream configStream = ObslugaXSL.class.getResourceAsStream("fop-conf.xml")) {

			JAXBContext ctx = JAXBContext.newInstance(obj.getClass());
			JAXBSource src = new JAXBSource(ctx, obj);

			FopFactory fopFactory = FopFactory.newInstance(new URI(""), configStream);

			try(BufferedOutputStream pdfOut = new BufferedOutputStream(output)) {
				Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, pdfOut);
				TransformerFactory tf = TransformerFactory.newInstance();
				StreamSource xsl = new StreamSource(ObslugaXSL.class.getResourceAsStream("sklep-fo.xsl"));
	
				Transformer tr = tf.newTransformer(xsl);
				Result res = new SAXResult(fop.getDefaultHandler());
				tr.transform(src, res);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new WebApplicationException("Problem FOP " + e.getMessage(), 500);
		}
	}

}





