package compackage;

// Java
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.IOException;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXResult;
import org.apache.xerces.impl.dv.util.Base64;

// FOP
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;

/**
 *
 * @author daisukeo
 */
@WebService()
public class NewWebService1 {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getCreatePDF")
    public String getCreatePDF(@WebParam(name = "parameter")
    String parameter) {

        FopFactory fopFactory = FopFactory.newInstance();
        OutputStream out = null;
        String finalResponse = "";

        try {
            //Input FO
            File fo = new File("incoming.fo");
            FileOutputStream fos = new FileOutputStream(fo);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter bos = new BufferedWriter(osw);
            bos.write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + parameter);
            bos.close();
            osw.close();
            fos.close();

            //Output PDF
            File pdf = new File("C:\\Temp\\ResultFO2PDF.pdf");

            // configure foUserAgent
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            fopFactory.setUserConfig(new File("C:\\Temp\\mycfg.xml"));

            //Set writing to PDF
            out = new FileOutputStream(pdf);
            out = new BufferedOutputStream(out);

            // Construct fop with desired output format
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

            // Setup JAXP using identity transformer
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();

            // Setup input stream
            Source src = new StreamSource(fo);
            
            // Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(fop.getDefaultHandler());

            // Start XSLT transformation and FOP processing
            transformer.transform(src, res);


            try
            {
                out.close();
            } catch(IOException ioe) {
                return null;
            }

            InputStream istream = new FileInputStream(pdf);
            // Get the size of the file
            long length = pdf.length();
            if (length > Integer.MAX_VALUE) {
                // File is too large
            }
            // Create the byte array to hold the data
            byte[] bytes = new byte[(int)length];

            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                   && (numRead=istream.read(bytes, offset, bytes.length-offset)) >= 0) {
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read file ");
            }

            // Close the input stream and return bytes
            istream.close();
            finalResponse =Base64.encode(bytes);

        } catch (Exception e) {
            return null;

        }

        return "<Quotation><PurchaseOrder><PurchaseOrderFile>"
                + "<File fileName=\"PurchaseOrder.pdf\">" + finalResponse
                + "</File></PurchaseOrderFile></PurchaseOrder></Quotation>";
    }
}