/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2013 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com
 * 
 * Unless you have purchased a commercial license agreement from Jaspersoft,
 * the following license terms apply:
 * 
 * This program is part of iReport.
 * 
 * iReport is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * iReport is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with iReport. If not, see <http://www.gnu.org/licenses/>.
 */

package com.jaspersoft.ireport.designer.crosstab;

import com.jaspersoft.ireport.designer.AbstractReportObjectScene;
import com.jaspersoft.ireport.designer.IReportManager;
import com.jaspersoft.ireport.designer.JrxmlVisualView;
import com.jaspersoft.ireport.designer.ModelUtils;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.JButton;
import net.sf.jasperreports.crosstabs.JRCellContents;
import net.sf.jasperreports.crosstabs.JRCrosstabCell;
import net.sf.jasperreports.crosstabs.JRCrosstabColumnGroup;
import net.sf.jasperreports.crosstabs.JRCrosstabRowGroup;
import net.sf.jasperreports.crosstabs.design.JRDesignCellContents;
import net.sf.jasperreports.crosstabs.design.JRDesignCrosstab;
import net.sf.jasperreports.crosstabs.fill.calculation.BucketDefinition;
import net.sf.jasperreports.crosstabs.type.CrosstabTotalPositionEnum;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
final class CrosstabDebugConsoleTopComponent extends TopComponent {

    private static CrosstabDebugConsoleTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";

    private static final String PREFERRED_ID = "CrosstabDebugConsoleTopComponent";

    private CrosstabDebugConsoleTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(CrosstabDebugConsoleTopComponent.class, "CTL_CrosstabDebugConsoleTopComponent"));
        setToolTipText(NbBundle.getMessage(CrosstabDebugConsoleTopComponent.class, "HINT_CrosstabDebugConsoleTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
        
    }

    private JButton createButton(CellInfo ci)
    {
        JButton b = new JCellButton(ci);
        return b;
    }

    private GridBagConstraints createConstraints(CellInfo ci, int crosstabWidth, int crosstabHeight)
    {
        return new GridBagConstraints(ci.getX(), ci.getY(), ci.getColSpan(), ci.getRowSpan(), ci.getCellContents().getWidth()*1.0/crosstabWidth , ci.getCellContents().getHeight()*1.0/crosstabHeight, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(0,0,0,0), 0,0);
    }
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();

        org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(CrosstabDebugConsoleTopComponent.class, "CrosstabDebugConsoleTopComponent.jButton1.text")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new java.awt.GridLayout(1, 0));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jButton1)
                .add(88, 88, 88))
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButton1)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        jPanel1.removeAll();

        JrxmlVisualView view = IReportManager.getInstance().getActiveVisualView();
        if (view == null)
        {
            jPanel1.updateUI();
            return;
        }

        // find the selected crosstab...
        AbstractReportObjectScene scene = view.getReportDesignerPanel().getActiveScene();

        if (scene instanceof CrosstabObjectScene)
        {

            List<CellInfo> cellInfos = new ArrayList<CellInfo>();
            JRDesignCrosstab crosstab = ((CrosstabObjectScene)scene).getDesignCrosstab();
            // Add columns...

            JRCrosstabRowGroup[] row_groups = crosstab.getRowGroups();
            JRCrosstabColumnGroup[] col_groups = crosstab.getColumnGroups();

            Point size = new Point(0,1);

            for (int i=0; i<row_groups.length; ++i)
            {
                size.x++;
            }


            for (int i=0; i<col_groups.length; ++i)
            {
                JRCrosstabColumnGroup group = col_groups[i];
                size.x++;
                if (group.getTotalPositionValue() !=  CrosstabTotalPositionEnum.NONE)
                {
                    size.x++;
                }
            }

            jPanel1.setLayout(new GridBagLayout());

            int x =0;
            int y =0;


            // Add header cell...
            if (crosstab.getHeaderCell() != null)
            {
                CellInfo ci = new CellInfo(x, y, row_groups.length, col_groups.length, crosstab.getHeaderCell());
                cellInfos.add(ci);
            }

            x = row_groups.length;
            y = 0;

            // Add column headers...
            int w = col_groups.length;
            int h = col_groups.length;


            for (int i=0; i<col_groups.length; ++i)
            {
                JRCrosstabColumnGroup group = col_groups[i];

                if (group.getTotalPositionValue() !=  CrosstabTotalPositionEnum.START)
                {
                    CellInfo ci = new CellInfo(x, y, 1, h, group.getTotalHeader());
                    cellInfos.add(ci);
                    x++;
                }

                CellInfo ci2 = new CellInfo(x, y, w, 1, group.getHeader());
                cellInfos.add(ci2);


                if (group.getTotalPositionValue() !=  CrosstabTotalPositionEnum.END)
                {
                     CellInfo ci = new CellInfo(x+w, y, 1, h, group.getTotalHeader());
                     cellInfos.add(ci);
                }

                w--;
                h--;
                y++;
            }


            x = 0;
            y = col_groups.length;

            // Add column headers...
            w = row_groups.length;
            h = row_groups.length;

            for (int i=0; i<row_groups.length; ++i)
            {
                JRCrosstabRowGroup group = row_groups[i];

                if (group.getTotalPositionValue() !=  CrosstabTotalPositionEnum.START)
                {
                    CellInfo ci = new CellInfo(x, y, w, 1, group.getTotalHeader());
                    cellInfos.add(ci);
                    y++;
                }

                CellInfo ci2 = new CellInfo(x, y, 1, h, group.getHeader());
                cellInfos.add(ci2);

                if (group.getTotalPositionValue() !=  CrosstabTotalPositionEnum.END)
                {
                    CellInfo ci = new CellInfo(x, y+h, w, 1, group.getTotalHeader());
                    cellInfos.add(ci);
                }

                w--;
                h--;
                x++;
            }


            x = row_groups.length;
            y = col_groups.length;

            JRCrosstabCell[][] cells = crosstab.getCells();
            cells = ModelUtils.normalizeCell(cells, row_groups, col_groups);
            for (int i=0; i<cells.length; ++i)
            {
                for (int k=0; k<cells[i].length; ++k)
                {
                    int cx = x + cells[i].length-k-1;
                    int cy = y + cells.length-i-1;
                    if (cells[i][k] == null)
                    {
                        continue;
                    }
                    String cellName = ModelUtils.nameOf( (JRDesignCellContents)(cells[i][k].getContents()));
                    CellInfo ci = new CellInfo(cx, cy, 1, 1, cells[i][k].getContents());
                    cellInfos.add(ci);
                }
            }




            int crosstabWidth = 1;
            int crosstabHeight = 1;
            for (int i=0; i < cellInfos.size(); ++i)
            {
                CellInfo ci = cellInfos.get(i);
                // calculate the width...
                // find the max with of the CI with x = ci.getX();
                int posX = 0;
                int posY = 0;

                for (int index = 0; index < ci.getX(); ++index)
                {

                    for (int k=0; k < cellInfos.size(); ++k)
                    {
                        CellInfo ci2 = cellInfos.get(k);
                        if (ci2.getX() == index)
                        {
                            posX += ci2.getCellContents().getWidth();
                            break;
                        }
                    }
                }

                ci.setLeft(posX);
                int thisW = ci.getLeft() + ci.getCellContents().getWidth();
                if (thisW > crosstabWidth) crosstabWidth = thisW;

                for (int index = 0; index < ci.getY(); ++index)
                {
                    for (int k=0; k < cellInfos.size(); ++k)
                    {
                        CellInfo ci2 = cellInfos.get(k);
                        if (ci2.getY() == index)
                        {
                            posY += ci2.getCellContents().getHeight();
                            break;
                        }
                    }
                }
                
                ci.setTop(posY);

                int thisH = ci.getTop() + ci.getCellContents().getHeight();
                if (thisH > crosstabHeight) crosstabHeight = thisH;
            }

            for (int i=0; i < cellInfos.size(); ++i)
            {
                CellInfo ci = cellInfos.get(i);
                jPanel1.add(createButton(ci), createConstraints(ci, crosstabWidth, crosstabHeight));
            }

            jPanel1.updateUI();

        }
    }//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized CrosstabDebugConsoleTopComponent getDefault() {
        if (instance == null) {
            instance = new CrosstabDebugConsoleTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the CrosstabDebugConsoleTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized CrosstabDebugConsoleTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(CrosstabDebugConsoleTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof CrosstabDebugConsoleTopComponent) {
            return (CrosstabDebugConsoleTopComponent) win;
        }
        Logger.getLogger(CrosstabDebugConsoleTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return CrosstabDebugConsoleTopComponent.getDefault();
        }
    }
}

