/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package puntocassa;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import java.awt.Color; 
import java.awt.Cursor;
import java.util.ArrayList;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.jasper.constant.JasperProperty;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.builder.subtotal.AggregationSubtotalBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;
/**
 *
 * @author Marco
 */
public class JInternalReport extends javax.swing.JInternalFrame {
    MyApplication MyA=new MyApplication();
    public String TitoloReport = "Regione Toscana - Punto Cassa ";
    String Ditta="Regione Toscana";
    private StyleBuilder boldStyle;
    private TextColumnBuilder<Float> ColonnaPrezzi;

    public void CreaReport(String[] Col, String[] ColType, Object[][] data) {
       

        StyleBuilder boldStyle = stl.style().bold();
        //scegliere il size del font
        StyleBuilder FontStyle = stl.style().setFontSize(7);
        StyleBuilder boldCenteredStyle = stl.style(boldStyle).setHorizontalAlignment(HorizontalAlignment.CENTER);
        StyleBuilder boldLeftStyle = stl.style(boldStyle).setHorizontalAlignment(HorizontalAlignment.LEFT);
        StyleBuilder columnTitleStyle = stl.style(boldCenteredStyle).setBorder(stl.pen1Point()).setBackgroundColor(Color.LIGHT_GRAY);

        ArrayList<TextColumnBuilder> columns = new ArrayList<TextColumnBuilder>();
        
        TextColumnBuilder<Float> itemColumn= null;
        TextColumnBuilder<Integer> itemPosizione= null;
        MyApplication MyA=new MyApplication();
        for (int i = 0; i < Col.length; i++) {
            if (Col[i].toString().equalsIgnoreCase("Codice")) {
            } else {
                
                switch (ColType[i]) {
                    case "text":
                        TextColumnBuilder<String> textColumn =  col.column(Col[i].replace("_", " "), Col[i], type.stringType());
                        textColumn.setHorizontalAlignment(HorizontalAlignment.CENTER);
                        columns.add(textColumn);
                        
                        break;
                    case "integer":
                        TextColumnBuilder<Integer> integerColumn = col.column(Col[i].replace("_", " "), Col[i], type.integerType());
                        
                        columns.add(integerColumn);
                        if (Col[i].equalsIgnoreCase(MyA.reportColonnaGroupBy)){
                            itemPosizione=integerColumn;
                        }
                        break;
                    case "boolean":
                        //TextColumnBuilder<Boolean> booleanColumn = col.column(Col[i], Col[i].replace(" ", "_"), type.booleanType());
                        TextColumnBuilder<String> booleanColumn =  col.column(Col[i].replace("_", " "), Col[i], type.stringType());
                        booleanColumn.setHorizontalAlignment(HorizontalAlignment.CENTER);
                        columns.add(booleanColumn);
                        break;
                    case "float":
                        TextColumnBuilder<Float> floatColumn = col.column(Col[i].replace("_", " "), Col[i], type.floatType());
                        floatColumn.setPattern("#,##0.00");
                        columns.add(floatColumn);
                   
                        if (Col[i].equalsIgnoreCase(MyA.reportColonnaSomma)){
                            itemColumn=floatColumn;
                        }
                        ColonnaPrezzi=floatColumn;
                        break;
                }
            }
        }

        //TextColumnBuilder<BigDecimal> unitPriceColumn = col.column("Unit price", "unitprice", type.bigDecimalType());
        //price = unitPrice * quantity 
        //TextColumnBuilder<BigDecimal> priceColumn = unitPriceColumn.multiply(quantityColumn).setTitle("Price");
        //PercentageColumnBuilder pricePercColumn = col.percentageColumn("Price %", priceColumn);
        /*TextColumnBuilder<Integer> rowNumberColumn = col.reportRowNumberColumn("No.")
         //sets the fixed width of a column, width = 2 * character width 
         .setFixedColumns(2)
         .setHorizontalAlignment(HorizontalAlignment.CENTER);*/
        try {
           
            JasperReportBuilder myReport;
            
            myReport = report()
                    .setColumnTitleStyle(columnTitleStyle)
                    .highlightDetailEvenRows()
                    .subtotalsAtSummary(createSubtotal("Totale"))
                    // .columns()
                    //.columns(columns)

                    // rowNumberColumn, textColumn, integerColumn, floatColumn)
                    .title(cmp.text(Ditta).setStyle(boldLeftStyle),cmp.text(TitoloReport).setStyle(boldCenteredStyle),cmp.image("..\\risorse\\logoStampa.jpg").setDimension(50,50))//shows report title 
                    //.title(cmp.image("pictures\\logoStampa.jpg").setFixedHeight(50),cmp.text(Ditta).setStyle(boldLeftStyle),cmp.text(TitoloReport).setStyle(boldCenteredStyle))//shows report title 

                    .pageFooter(cmp.pageXofY().setStyle(boldCenteredStyle))//shows number of page at page footer 
                    //.setDataSource(createDataSource(Col,data))//set datasource 
                    .setPageFormat(PageType.A5, PageOrientation.LANDSCAPE) 
                     //.setPageMargin(margin(20)) 
                    //.groupBy(itemColumn)
                    
                    
                    //assegna la grandezza del font al corpo del report
                    .setColumnStyle(FontStyle)


                    .setDataSource(createDataSource(Col,ColType, data));
            
                    for (int i = 0; i < columns.size(); i++) {
                        columns.get(i).setStretchWithOverflow(true);
                        columns.get(i).addProperty(JasperProperty.PRINT_KEEP_FULL_TEXT, "true");
                        Integer Pos=MyA.elencoColonneReport.indexOf(";" + i + "|");
                        if (Pos>=0){
                            Integer PosF=MyA.elencoColonneReport.indexOf(";",Pos+1);
                            String T=MyA.elencoColonneReport.substring(Pos, PosF);
                            String E[]=T.split("\\|");
                            columns.get(i).setFixedWidth(Integer.parseInt(E[1]));
                        }
                        myReport.columns(columns.get(i));
                        
                    }
                    
                                        
//                   if (MyA.reportColonnaGroupBy.length()>0){
//                       myReport.groupBy(itemPosizione); 
//                       myReport.subtotalsAtSummary(sbt.sum(itemColumn)); 
//                       //myReport.subtotalsAtFirstGroupFooter(sbt.sum(itemPosizione),sbt.sum(itemColumn)); 
//                    }
                   MyA.reportColonnaGroupBy="";MyA.elencoColonneReport="";
                    JasperPrint reportPrint = myReport.toJasperPrint();
                    JasperViewer reportViewer = new JasperViewer(
                            DefaultJasperReportsContext.getInstance(),
                    reportPrint,
                    false,
                    null,
                    null
            );

            reportViewer.setTitle(TitoloReport);
            
            reportViewer.setVisible(true);

            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        } catch (DRException e) {
            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            e.printStackTrace();

        }

    }

    private AggregationSubtotalBuilder<Float> createSubtotal(String label) {
        boldStyle = stl.style().bold().setHorizontalAlignment(HorizontalAlignment.RIGHT);

        return sbt.sum(ColonnaPrezzi).setLabel(label).setLabelStyle(boldStyle);

    }


    private JRDataSource createDataSource(String[] Col,String[] ColType, Object[][] data) {

        //DRDataSource dataSource = new DRDataSource("item", "quantity", "unitprice"); 
        
        //dataSource.add("Notebook", 1, new BigDecimal(500));
        if (Col[0].toString().equalsIgnoreCase("Codice")) {
           String[] Col2=new String[Col.length-1];
           for(int i=1;i<Col.length;i++){
                Col2[i-1]=Col[i].replace(" ", "_");
           }
            DRDataSource dataSource = new DRDataSource(Col2);
            for (int r = 0; r < data.length; r++) {
                Object[] row = new Object[data[r].length - 1];
                for (int i = 1; i < data[r].length; i++) {
                    

                    if (Col[i].toString().equalsIgnoreCase("Codice")) {
                    } else {

                        switch (ColType[i]) {
                            case "text":
                                if(data[r][i]==null){row[i - 1] ="";}else{row[i - 1] = data[r][i].toString();}
                                
                                break;
                            case "integer":
                                if(data[r][i]==null){}else{row[i - 1] =Integer.parseInt(data[r][i].toString());}
                                
                                break;
                            case "boolean":
                                if (data[r][i] != null) {
                                    if (data[r][i].toString().equalsIgnoreCase("false")) {
                                        row[i - 1] = "No";
                                    } else {
                                        row[i - 1] = "Sì";
                                    }
                                }
//if(data[r][i]==null){row[i - 1] =false;}else{row[i - 1] =Boolean.parseBoolean(data[r][i].toString());}

                                break;
                            case "float":
                                if(data[r][i]==null){}else{row[i - 1] =Float.parseFloat(data[r][i].toString());}
                                
                                break;
                        }
                    }
                }
                dataSource.add(row);


            }
           return dataSource;
        } else {
            DRDataSource dataSource = new DRDataSource(Col);
//            Double tot= 0.0;
            for (int r = 0; r < data.length; r++) {
                dataSource.add(data[r]);
//                tot=tot + Float.parseFloat(data[r][1].toString());
            }
            
//            Object[][] RigaTotale=new Object[1][2];
//            RigaTotale[0][0]="Totale";
//            RigaTotale[0][1]=tot;
//            dataSource.add(RigaTotale);
            return dataSource;
        }
    }

    /**
     * Creates new form JframeReport
     */


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents



    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
