// Ellectra-Web - Document conversion

package eu.ellectraweb.framework.components;

// Java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

//JAXP
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.sax.SAXResult;


// 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.FormattingResults;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.apps.PageSequenceResults;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;


/**
 * This class performs the XML document conversion using FOP.
 */
public class Converter {
    
	// TODO: Path of the xslt transformations. Change according to location.
    private String xsltPath = "C:\\Eclipse_ePP_AF\\AllInOneWorkspace\\ELLECTRA-WeB\\eu.ellectraweb.framework.components\\Components\\Document conversion\\dist";
    //private String xsltPath = "C:\\workspaces\\Ellectra\\ellectraweb\\eu.ellectraweb.framework.components\\Components\\Document conversion\\dist";
   // private String confPath = "C:\\workspaces\\Ellectra\\ellectraweb\\eu.ellectraweb.framework.components\\Components\\Document conversion\\dist\\fop-conf.xml";
    private String confPath =  "C:\\Eclipse_ePP_AF\\AllInOneWorkspace\\ELLECTRA-WeB\\eu.ellectraweb.framework.components\\Components\\Document conversion\\dist\\fop-conf.xml";
    public String Convert(String formType, String inputFile, String mime, String language) {
        if (mime.compareTo(MimeConstants.MIME_PDF) == 0) {
            return convertXML2PDF(formType, inputFile, language);
        }
        else if (mime.compareTo(MimeConstants.MIME_PLAIN_TEXT) == 0) {
            return convertXML2HTML(formType, inputFile, language);
        }
        else return "Unknown MIME type";
    }

    public String convertXML2PDF(String formType, String inputXmlPath, String language) {
    	try {
    		if (!validateForm(formType))
    			return formType + " is not valid form type.";
    		
            int pos = inputXmlPath.lastIndexOf('\\');
            String rootPath = inputXmlPath.substring(0, pos);
            String xmlFileName = inputXmlPath.substring(pos+1);
            String xmlFileWithoutExt = xmlFileName.substring(0, xmlFileName.indexOf('.'));
            
            // Setup directories
            File baseDir = new File(xsltPath);
            File outDir = new File(rootPath);
            
            // Setup input and output files            
            File xmlfile = new File(outDir, xmlFileName);
            File xsltfile = new File(baseDir, "xslt-fo\\" + formType + "-" + language + ".xslt");
            File pdffile = new File(outDir, xmlFileWithoutExt + ".pdf");
 
            // configure fopFactory as desired
            FopFactory fopFactory = FopFactory.newInstance();
            fopFactory.setUserConfig(new File(confPath)); 
           
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
            // configure foUserAgent as desired

            // Setup output
            OutputStream out = new java.io.FileOutputStream(pdffile);
            out = new java.io.BufferedOutputStream(out);
            
            try {
                // Construct fop with desired output format
                Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
    
                // Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
                
                if (transformer == null)
                    throw new Exception("Transformer object did not created.");
                
                // Set the value of a <param> in the stylesheet
                transformer.setParameter("versionParam", "2.0");
            
                // Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);
             
                // 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);
                
                return "File saved in: " + pdffile.getPath();
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                out.close();
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    
    public String convertXML2HTML(String formType, String inputXmlPath, String language)
     {
       try {
    	   if (!validateForm(formType))
   			return formType + " is not valid form type.";
    	   
            int pos = inputXmlPath.lastIndexOf('\\');
            String rootPath = inputXmlPath.substring(0, pos);
            String xmlFileName = inputXmlPath.substring(pos+1);
            String xmlFileWithoutExt = xmlFileName.substring(0, xmlFileName.indexOf('.'));
            
            // Setup directories
            File baseDir = new File(xsltPath);
            File outDir = new File(rootPath);

            File xmlfile = new File(outDir, xmlFileName);
            File xsltfile = new File(baseDir, "xslt\\" + formType + "-" + language + ".xslt");
            File htmlFile = new File(outDir, xmlFileWithoutExt + ".html");
            //Setup output
            OutputStream out = new java.io.FileOutputStream(htmlFile);
            try {
                //Setup XSLT
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));

                if (transformer == null)
                    throw new Exception("Transformer object did not created.");
                
                //Setup input for XSLT transformation
                Source src = new StreamSource(xmlfile);

                //Resulting SAX events (the generated FO) must be piped through to FOP
                Result res = new StreamResult(out);

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

                return "File saved in: " + htmlFile.getPath();
            } catch (Exception e) {
                return e.getMessage();
            } finally {
                out.close();
            }
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    private boolean validateForm(String formType) {
    	return formType.compareTo("F01_PRIOR_INFORMATION") == 0 
    			|| formType.compareTo("F02_CONTRACT") == 0
    			|| formType.compareTo("F03_CONTRACT_AWARD") == 0
    			|| formType.compareTo("F04_PERIODIC_INDICATIVE_UTILITIES") == 0
    			|| formType.compareTo("F05_CONTRACT_UTILITIES") == 0
    			|| formType.compareTo("F06_CONTRACT_AWARD_UTILITIES") == 0
    			|| formType.compareTo("F07_QUALIFICATION_SYSTEM_UTILITIES") == 0
    			|| formType.compareTo("F08_BUYER_PROFILE") == 0
    			|| formType.compareTo("F09_SIMPLIFIED_CONTRACT_DPS") == 0
    			|| formType.compareTo("F10_CONCESSION") == 0
    			|| formType.compareTo("F11_CONTRACT_CONCESSIONAIRE") == 0
    			|| formType.compareTo("F12_DESIGN_CONTEST") == 0
    			|| formType.compareTo("F13_RESULT_DESIGN_CONTEST") == 0;
    	}
    }
