import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;

import jet.api.CTAggFieldInfo;
import jet.api.CTRowColFieldInfo;
import jet.api.CrossTabInfo;
import jet.api.Designer;
import jet.api.DesignerErrorException;
import jet.api.DesignerUserInfo;
import jet.jetc.ReadFailureException;
import jet.universe.exception.UniverseFileException;
/**
 * This class creates a crosstab report with the name provided directly into a report tab. 
 * The crosstab is similar to ProductSalesAnalysis.cls in TutorialReports.
 * It requires the catalog JinfonetGourmetJava.cat
 * 
 * Usage TestInsertCrossTabIntoReport -path=<path> -catalog=<catalog> -report=<report> [-log=<log file>]
 */
public class TestInsertCrossTabIntoReport {

	Designer desg;

	public TestInsertCrossTabIntoReport(String path, String cat, String log)
			throws IOException, ReadFailureException, UniverseFileException {
		DesignerUserInfo userInfo = new DesignerUserInfo("Jinfonet","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
		desg = new Designer(path, cat, userInfo);
		if (log != null && log.length() > 0) {
			desg.setLog(new FileOutputStream(log), "8859_1");
		}
	}

	@SuppressWarnings("unchecked")
	public void insert(String name) throws DesignerErrorException {
		String handle, handles[], reportset, report, crosstab, insName;
	
		desg.deleteReportFile(name);

		// 1.Delete if present then create a new reportset
		desg.deleteReportFile(name);   
		reportset = desg.createReportSet(name);
		if (reportset != null) {
			// 2.Create a Dataset
			desg.addDataset(reportset, "Data Source 1",
					"OrderListbyDate", "OrderListbyDate", null,
					Designer.DATASET_TYPE_QUERY);
			//3.Create a  report tab
			report = desg.addReport(reportset, "myreport");
		
			// 4.Set report body property
			String reportBody = desg
					.getHandles(report, Designer.REPORTBODY, -1)[0];
			String p = desg.insertPage(report);
			desg.insertPageStartEnd(p, reportBody, 0, 0);
			//set dataset
			desg.bindDataSet(reportBody, "OrderListbyDate");

			desg.set(reportBody, "Width", 20);
			desg.set(reportBody, "Height", 4.2f);
			// Set the size of the page footer and add a page number
			String[] pageFooter = desg.getHandles(report, Designer.PAGEFOOTER, -1);
			desg.set(pageFooter[0], "Width", 3f);
			desg.set(pageFooter[0], "Height", 0.2f);
			desg.set(pageFooter[0], "Foreground", new Color(0x00ff00));
			// Add some labels to the page header
			String header = desg.getHandles(report, Designer.PAGEHEADER, -1)[0];
			desg.set(header, "Height", 1.5f);
			String label = desg.insert(header, Designer.LABEL, "Label1");
			desg.set(label, "Width", 5.97f);
			desg.set(label, "Height", 0.36f);
			desg.set(label, "Text", "Product Sales by Quarter (Crosstab)");
			desg.set(label, "X", 0.97f);
			desg.set(label, "Y", 0.30f);
			desg.set(label, "Foreground", new Color(0x000095));
			desg.set(label, "Bold", true);
			desg.set(label, "FontSize", 0.19f);
			label = desg.insert(header, Designer.LABEL, "Label2");
			desg.set(label, "Width", 2.33f);
			desg.set(label, "Height", 0.2f);
			desg.set(label, "Text", "Units and Sales Total");
			desg.set(label, "X", 2.05f);
			desg.set(label, "Y", 0.73f);
			desg.set(label, "Bold", true);
			desg.set(label, "FontSize", 0.13f);
			
			//5.Create a CrosstabInfo
			Vector clmFldInfos = new Vector();
			// Formula QuarterOfOrderDate in columns
			clmFldInfos.add(new CTRowColFieldInfo("Col1", "QuarterOfOrderDate", CTRowColFieldInfo.ASCENDING, null));
			Vector rowFldInfos = new Vector();
			// DBField Product Name in rows
			rowFldInfos.add(new CTRowColFieldInfo("Row1", "Product Name", CTRowColFieldInfo.ASCENDING, null));
			Vector smrFldInfos = new Vector();
			smrFldInfos.add(new CTAggFieldInfo("Agg1", "Quantity", CTAggFieldInfo.SUM,1,"Units"));
			smrFldInfos.add(new CTAggFieldInfo("Agg2", "Total", CTAggFieldInfo.SUM,2,"Total"));
			CrossTabInfo cti = new CrossTabInfo("OrderListbyDate",clmFldInfos,rowFldInfos,smrFldInfos,-1,false);

			//6.insert a crosstab into the ReportBody and set the width
			crosstab = desg.insertCrossTab(reportBody, cti);
			// set width of aggregate labels
			handles = desg.getHandles(crosstab, Designer.CTHDTEXTFIELD, -1);
			desg.set(handles[0], "Width", 0.5f);
			// set width of row dbfield
			handles = desg.getHandles(crosstab, Designer.CTHDDBFIELD, -1);
			desg.set(handles[0], "Width", 1.5f);
			
			if (desg.getError() == null) {
				System.out.println(" crosstab inserted ok!");
			} else {
				System.out.println(desg.getError());
			}
			handles = desg.getHandles(crosstab, Designer.CTAGGFIELD, -1);
			for ( int i = handles.length; --i >= 0; )
			{
				handle = handles[i];
				insName = desg.getInstanceName(handle);
				System.out.println("handle = " + handle + " - Instance = " + insName);
				desg.set(handle, "Foreground", insName.startsWith("QUANTITY_")  ? new Color(0x0000a0) : new Color(0xa00000));
				if ( insName.startsWith("TOTAL_") )
				{
					desg.set(handle, "Width", 1.08f);
					desg.set(handle, "Format", "$#,##0.00");
				}
				else if (insName.startsWith("QUANTITY_"))
				{
					desg.set(handle, "Format", "#,###");
				}
			}
		}
		desg.exit();

	}
    // parameter tokens
    private final static String pathArg = "-path=";
    private final static String catArg = "-catalog=";
    private final static String rptArg = "-report=";
    private final static String logArg = "-log=";

    private final static void showUsage() {
        System.out.println( "TestInsertCrossTabIntoReport - programattically define a crosstab inserted directly into a report.");
        System.out.println( "Usage:  java TestInsertCrossTabIntoReport <-options>");
        System.out.println("\nwhere options include:");
        System.out.println("    " + pathArg +   "<path to catalog>  indicates the full path name to the report catalog directory");
        System.out.println("    " + catArg +    "<catalog name>  indicates the name of the report catalog");
        System.out.println("    " + rptArg +    "<report name>  indicates the name of the report to create");
        System.out.println("    " + logArg +    "<log file path and name>   indicates to log to this file, defined by full path name");
        System.out.println("\nExample to create and define a report from the command line:");
        System.out.println("java TestDesignInvoice -path=C:\\JReport\\Designer\\Demo\\Reports\\TutorialReports  -catalog=JinfonetGourmetJava.cat  -report=TestCrosstab.cls -log=C:\\JReport\\Designer\\logs\\designer.log");
    }

    public static void main(String argv[])
    {
        // values of command line arguments.
        String path = "";
        String catalog = "";
        String report = "";
        String log = "";
        Boolean usage;

        // get values of command line arguments
        for (int i = 0; i < argv.length; i++) {
            if (argv[i].toLowerCase().startsWith(catArg)) {
                catalog = argv[i].substring(catArg.length(), argv[i].length());
            } else if (argv[i].toLowerCase().startsWith(rptArg)) {
                report = argv[i].substring(rptArg.length(), argv[i].length());
            } else if (argv[i].toLowerCase().startsWith(pathArg)) {
                path = argv[i].substring(pathArg.length(), argv[i].length());
            } else if (argv[i].toLowerCase().startsWith(logArg)) {
                log = argv[i].substring(logArg.length(), argv[i].length());
            } else {
                // is not a valid command line argument
                showUsage();
                System.exit(1);
            }
         }    

        // log file is an optional parameter.
        // path, catalog, and report are required parameters.
        if ( (path.length() == 0) || (catalog.length() == 0) || report.length() == 0 ) {
                showUsage();
                System.exit(1);
        }

        System.out.println("Catalog = " + catalog);
        System.out.println("   Path = " + path);
        System.out.println(" Report = " + report);
        System.out.println("    Log = " + ((log==null) ? "" : log));
        
		if (path.length() > 0 && catalog.length() > 0 && report.length() > 0) 
		{
				try 
				{
					TestInsertCrossTabIntoReport test = new TestInsertCrossTabIntoReport(path, catalog,
							log);
					test.insert(report);
					System.out.println("\nReport "+ report + " was successfully created in " + path);
				} 
				catch (Exception e) 
				{
					e.printStackTrace();
					showUsage();
				}
		} 
        else 
		{
			showUsage();
		}
		
		System.exit(0);
	}
}
