package examples.report;

import java.io.IOException;

import de.vc.jfo.importer.ImportParameters;
import de.vc.jfo.renderer.OutputFormat;
import de.vc.jfo.renderer.Renderer;
import de.vc.jfo.renderer.RendererFactory;
import de.vc.jfo.report.FOReportBuilder;
import de.vc.jfo.tools.FontMapper;
import de.vc.report.DataSource;
import de.vc.report.ReportEngine;
import de.vc.report.ReportStorage;
import de.vc.report.sources.xml.XMLDataSource;
import de.vc.report.storages.FileStorage;

/**
 * This example shows how to create reports from a xml source that has
 * report nodes but also foreign (non-report) nodes. This example is very
 * equal to ReportXMLSource.java, the only differences are the XML
 * source file and the creation of data source in method createDataSource().
 * @author not attributable
 * @version 1.0
 */
public class ReportMixedXMLSource {

  private final static String XML_SOURCE  = "docs-in/report/music-ds-mixed.xml";
  private final static String RTF_FILE  = "docs-in/report/music-template.rtf";
  private final static String REPORT_DIR  = "docs-out/report/reports";
  private final static String IMAGE_DIR = "docs-out/report/images";


  public static void main(String[] args) throws Exception{

    // Create a data-source that delivers data for each report
    DataSource ds = createDataSource();

    // Where to put generated reports...
    ReportStorage storage = new FileStorage( REPORT_DIR, "music-", "-mixed-xml");

    // Our report-engine is not XSL-FO specific, so we need a
    // special report builder used by our report-engine.
    FOReportBuilder reportBuilder = new FOReportBuilder(
        RTF_FILE,
        getParameters()
    );


    // Or render to any other format
    OutputFormat format = OutputFormat.PDF;
    Renderer r = RendererFactory.instance().getRenderer(format);

    if (r!=null)
      reportBuilder.setOutputFormat( format, r );
    else
      System.out.println("No renderer found for "+format+". Is FOP in classpath?");


    // Now we can create the engine and run it.
    ReportEngine engine = new ReportEngine(ds, reportBuilder, storage);
    engine.run();

  }


  private static DataSource createDataSource() throws IOException{
    XMLDataSource ds = new XMLDataSource(XML_SOURCE);
    ds.setIgnoreForeignNodes(true);
    return ds;
  }


  /**
   * Create parameters for RTF import (used by FOReportBuilder).
   * @return Import parameters.
   */
  private static ImportParameters getParameters(){
    ImportParameters params = new ImportParameters();

    // Path for images
    params.setImagePath(IMAGE_DIR);

    // If you don't set a font mapper, the font-mapping
    // in jfo-config file is used.
    // In case of any question about font-mapping please read the
    // user manual.
    FontMapper fm = new FontMapper();
    fm.addMappingRule("Times*", "Times");
    fm.addMappingRule("Arial*", "Helvetica");
    params.setFontMapper(fm);

    return params;
  }
}
