
import java.io.*;
import java.util.HashMap;
import jet.api.*;
import jet.jetc.*;
import jet.universe.exception.*;

/**
 * This class creates a report specified by the report parameter, the report is similar to AnnualSalesbyRegion.cls in the TutorialReports.
 * It requires the catalog JinfonetGourmetJava.cat
 * Usage TestDesignGraph -path=<path> -catalog=<catalog> -report=<report> [-log=<log file>]
 */
 
public class TestDesignGraph
{
	Designer desg;
	String errorMsg = null;     // Holds error message related to a failure that is visible to main().
	HashMap<Integer, String> handleNames = new HashMap<Integer, String>();
	
	/**
	 * Constructor. Create a new TestDesignGraph object.
	 * @param path The path of catalog folder.
	 * @param cat The name of catalog.
	 * @param log AbsolutePath of log.
	 */
	public TestDesignGraph(String path, String cat, String log) throws IOException, ReadFailureException, UniverseFileException
	{
		DesignerUserInfo userInfo=new DesignerUserInfo("Jinfonet", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
		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");

	}

	/**
	 * Show the handles of the current report structure, to assist in debugging programs using the Designer class methods.
	 * @param label The message your input.
	 */
	    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;
	    }
	/**
	 * Create report according to parameter name.
	 * @throws DesignerErrorException 
	 * @param  name The name of report
	 * @return If create report fault return false.
	 */
	public boolean create(String name) throws DesignerErrorException
	{
		String  report, dataset, reportbody, reportset;
		Boolean ret = false;
        
		// Delete old <report>.cls if it is present
		desg.deleteReportFile(name);
		
		// 1. Create new <report>.cls
		reportset = desg.createReportSet(name);
		if (reportset == null) {
            this.errorMsg = "Failure addDataSet(): " + desg.getError();
            return false;
        }
		
		// 2. Register the existing query "OrderListbyDate" to this report set.
        dataset = desg.addDataset(reportset, "Data Source 1", "AnnualSalesbyRegion","QueryDataSet","",Designer.DATASET_TYPE_QUERY);        
        if (dataset == null) {
            this.errorMsg = "Failure addDataSet(): " + desg.getError();
            return false;
        }
                  
        // 3. Create the named report tab within the Page Report
        //    For this example program, the name of the added report tab is hard coded.
        report = desg.addReport(reportset, "Chart");
        if (report == null) {
            this.errorMsg = "Failure addReport(): " + desg.getError();
            return false;
        }
 
            reportbody = desg.getHandles(report, Designer.REPORTBODY, -1)[0];
             
            // 4. Insert a PagePanel into the Invoice tab
            String page = desg.insertPage(report);             
            desg.insertPageStartEnd(page, reportbody, 0, 0);
            desg.set(page, "Width", 8.0f);
            desg.set(page, "Height", 9.2f);              
            showHandles("after insert page");
              
            String[] pageFooter = desg.getHandles(report, Designer.PAGEFOOTER,-1);
            desg.set(pageFooter[0], "Height", 0.2f);           

            
            // 5. Insert a chart
            ChartInfo chartInfo = new ChartInfo("Region_AbbreviationName","YearOfOrderDate");       
            chartInfo.SetChartShowType(Designer.BAR_SIDEBYSIDE_LINE_ARRAY_2D, false, "Sum_AnnualSalesbyRegion_AbbreviationName");
            ChartLabelInfo labelInfo = new ChartLabelInfo("ChartPaperObject","Annual Sales by Region","","","ChartLabelObject1","Regions");
            chartInfo.setChartLabelInfo(labelInfo);           
            ChartLegendInfo legendInfo = new ChartLegendInfo("ChartLegendObject",true,ChartLegendInfo.RIGHT);
            chartInfo.setChartLegendInfo(legendInfo);
            String chartHandle = desg.insertChart(reportbody, chartInfo);
            if(chartHandle == null){
            	this.errorMsg = "Failure insertChart(): " + desg.getError();
            	return false;
            }
            desg.set(chartHandle, "Height", 3.83f);
            desg.set(chartHandle, "Width", 5.07f);
            desg.set(chartHandle, "X", 0.14f);
			desg.set(chartHandle, "Y", 0.14f);
			
			// 6. bind the dataSet to the report body and set banded object to inherit the dataSet
            // it is an container object that must have a data set bound to it.
		    if( ! desg.bindDataSet(reportbody, "QueryDataSet") ) {
                 this.errorMsg = "Failure bindDataSet(): " + desg.getError();
                 return false;
               }
            desg.set(chartHandle, "dataInherit", true);

			ret = true;
		
        desg.exit();
		try
		{
			desg.closeLog();
		}
		catch ( IOException e )
		{
			e.printStackTrace();
		}
		return ret;
	}
	// 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=TestChart.cls -log=C:\\JReport\\Designer\\logs\\chart.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
				{
					TestDesignGraph test = new TestDesignGraph(path, catalog, log);
					if (test.create(report))
					{
						System.out.println("Successfully created " + report + " in "+ path);
					}
					else
					{
						System.out.println("Error creating " + report + ", check log file "+ log);
					}
				}
				catch ( Exception e )
				{
					e.printStackTrace();
					showUsage();
				}
			}
		else
		{
			showUsage();
		}

		System.exit(0);
	}
}
