import org.faceless.report.*;
import org.faceless.pdf2.*;
import org.xml.sax.*;
import java.io.*;

// Usage: java Sample test.xml [test2.xml test3.xml...]
//
// Create PDF documents from XML documents specified on the command line.
//
// The output file is the same as the input files, but with a ".pdf" suffix,
// e.g.  test.pdf, test2.pdf, test3.pdf
//
public class SampleApplication {

    public static void main(String[] args) throws SAXException {
	if (args.length == 0) {
	    System.err.println("Usage: java Sample <infile1.xml> [<infile2.xml> ...]");
	    System.exit(0);
	}
	System.out.println("---------------------------------------------------");
	System.out.println("Parsing files. Note the first file will take longer");
	System.out.println("as it must load various static resources.");
	System.out.println("---------------------------------------------------");

	ReportParser parser = ReportParser.getInstance();
        for (int i=0;i<args.length;i++) {
            doParse(parser, new File(args[i]));
        }

	System.out.println("---------------------------------------------------");
    }

    public static void doParse(ReportParser parser, File infile) {
        File outfile = new File(infile.getParent(),  infile.getName().replaceAll("\\.xml$", "")+".pdf");
        FileOutputStream out = null;

        try {
            System.out.print("Parsing \""+infile+"\"... ");
            long now = System.currentTimeMillis();
            PDF pdf = parser.parse(infile);
            out = new FileOutputStream(outfile);
            pdf.render(out);
            System.out.println("created \""+outfile+"\" in "+(System.currentTimeMillis()-now)+"ms");
        } catch (Exception e) {
            System.out.println();
            if (e instanceof SAXException && ((SAXException)e).getException() != null) {
                ((SAXException)e).getException().printStackTrace();
            } else {
                e.printStackTrace();
            }
        } finally {
            if (out != null) {
                try { out.close(); } catch (Exception e) {}
            }
        }
    }

}
