import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
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 banded report containing a crosstab with the name provided. 
 * 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 TestInsertCrossTabIntoBanded {

	Designer desg;
    HashMap<Integer, String> handleNames = new HashMap<Integer, String>();

	public TestInsertCrossTabIntoBanded(String path, String cat, String log)
			throws IOException, ReadFailureException, UniverseFileException {
		DesignerUserInfo userInfo = new DesignerUserInfo("Jinfonet","XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
		desg = new Designer(path, cat, userInfo);
		if (log != null && log.length() > 0) {
			desg.setLog(new FileOutputStream(log), "8859_1");
		}
        // Fill up hash map to support converting handle type to name, for logging.
        handleNames.put(new Integer(Designer.PAGE),        "Page");
        handleNames.put(new Integer(Designer.PAGEHEADER),  "Page Header");
        handleNames.put(new Integer(Designer.PAGEFOOTER),  "Page Footer");
        handleNames.put(new Integer(Designer.PAGEEND),     "Page End");
        handleNames.put(new Integer(Designer.PAGESTART),   "Page Start");
        handleNames.put(new Integer(Designer.DATASET),     "Dataset");
        handleNames.put(new Integer(Designer.BANDEDOBJECT_HEADER),     "Banded Object Header");
        handleNames.put(new Integer(Designer.BANDEDOBJECT_FOOTER),     "Banded Object Footer");
        handleNames.put(new Integer(Designer.BANDEDOBJECT),            "Banded Object");
        handleNames.put(new Integer(Designer.BANDEDOBJECT_PAGEHEADER), "Banded Object Page Header");
        handleNames.put(new Integer(Designer.BANDEDOBJECT_PAGEFOOTER), "Banded Object Page Footer");
        handleNames.put(new Integer(Designer.GROUPHEADER), "Group Header");
        handleNames.put(new Integer(Designer.GROUPFOOTER), "Group Footer");
        handleNames.put(new Integer(Designer.DETAIL),      "Detail");
        handleNames.put(new Integer(Designer.REPORTSET), "Report Set");
        handleNames.put(new Integer(Designer.REPORTBODY), "Report Body");
        handleNames.put(new Integer(Designer.DATAOBJECT),  "Data Container"); 
        handleNames.put(new Integer(Designer.REPORTSHEET), "Report Sheet");
        handleNames.put(new Integer(Designer.REPORTFOOTER),  "Report Footer"); 
        handleNames.put(new Integer(Designer.REPORTHEADER), "Report Header");
        handleNames.put(new Integer(Designer.CTAGGFIELD), "CT Aggregate Field");
        handleNames.put(new Integer(Designer.CTHDDBFIELD),  "CT Header Row or Column"); 
        handleNames.put(new Integer(Designer.CROSSTAB), "Crosstab Component");
        handleNames.put(new Integer(Designer.CTHDTEXTFIELD), "CT Aggregate Label");
        handleNames.put(new Integer(Designer.CTAGGINFO), "CT Row or Column Information");
	}
	/**
	 * Show the handles of the current report structure, to assist in debugging programs using the Designer class methods.
	 */
	    public void showHandles(String label)
	    {
	        Integer type;
	        String sType;
	        String handles[] = desg.getHandles();    
	        System.out.println("---- " + label + " --- size: " + handles.length + " ----");
	        for (int i = 0; i < handles.length; i++) {
	            type=desg.getObjectType(handles[i]);

	            // generate readable and output-formatted name of type
	            // intent is to show type and name and ignore unknown types
	            sType=handleNames.get(type);
	            if(sType != null) 
	            {
	            	sType="("+sType+")";
	            	System.out.println(handles[i] + "  Type: " + type + sType  );
	            }
	            else if (type != -1)
	            {
	            	System.out.println(handles[i] + "Type: " + type);
	            }
	        }
	        System.out.println("---- " + label + " --- end");
	   
	        return;
	    }
	public void insert(String name) throws DesignerErrorException {
		String handle, handles[], reportset, report, banded, dataset, pagepanel, crosstab, header = null, insName;

		desg.deleteReportFile(name);

		// 1.Create a reportset
		reportset = desg.createReportSet(name);
		if (reportset != null) {
			// 2.Create a Dataset
			dataset = desg.addDataset(reportset, "Data Source 1",
					"OrderListbyDate", "OrderListbyDate", null,
					Designer.DATASET_TYPE_QUERY);
			// 3.Create a report
			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);

			desg.set(reportBody, "Width", 20);
			desg.set(reportBody, "Height", 4.2f);

			String pageFooter = desg.getHandles(report, Designer.PAGEFOOTER,
					-1)[0];
			desg.set(pageFooter, "Width", 3f);
			desg.set(pageFooter, "Height", 0.2f);
			desg.set(pageFooter, "Foreground", new Color(0x00ff00));
			// Add some labels to the page header
			String pageHeader = desg.getHandles(report, Designer.PAGEHEADER, -1)[0];
			desg.set(pageHeader, "Height", 1.5f);
			String label = desg.insert(pageHeader, 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(pageHeader, 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.Insert banded object
			banded = desg.insertBandedObject(reportBody, true, true, true);
			//set dataset
			desg.bindDataSet(banded, "OrderListbyDate");
			desg.set(banded, "Width", 15);
			header = desg.getHandles(banded,Designer.BANDEDOBJECT_HEADER,-1)[0];
			desg.set(header,"Width", 15);
			desg.set(
							desg.getHandles(banded,Designer.BANDEDOBJECT_FOOTER,-1)[0],
							"Width", 15);
			desg.set(
							desg.getHandles(banded,Designer.BANDEDOBJECT_PAGEFOOTER,-1)[0],
							"Width", 15);
			desg.set(
							desg.getHandles(banded,Designer.BANDEDOBJECT_PAGEHEADER,-1)[0],
							"Width", 15);

			// 6.Create a CrosstabInfo
			Vector clmFldInfos = new Vector();
			clmFldInfos.add(new CTRowColFieldInfo("Col1", "QuarterOfOrderDate",
					CTRowColFieldInfo.ASCENDING, null));
			Vector rowFldInfos = new Vector();
			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);

			// 7.insert a crosstab in banded
			crosstab = desg.insertCrossTab(header,cti);
			
			showHandles("after adding crosstab");
			// 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("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( "TestInsertCrossTabIntoBanded - programattically define a banded report with crosstab inserted into the Banded Header.");
        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 TestInsertCrossTabInfoBanded -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 = "";

        // 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 
				{
					TestInsertCrossTabIntoBanded test = new TestInsertCrossTabIntoBanded(
							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);
	}
}
