/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/18, 13:47
!  AUTHOR(S): KOGA, Junichiro
!  File : GeneralAttributes.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */

package ciss.phase_viewer.plugins.graph.plotattributes;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

import org.apache.log4j.Logger;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.LegendItemSource;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleEdge;

import ciss.phase_viewer.common.FontChooser;
import ciss.phase_viewer.graph.plotattributes.PlotAttributesEditor;
import ciss.phase_viewer.graph.plotattributes.PlotAttributesSubEditor;

/**
 * グラフの, "general"な項目を編集.
 * 
 * @author
 */
public class GeneralAttributes extends PlotAttributesSubEditor {
    private Logger logger = Logger.getLogger(GeneralAttributes.class.getName());

    /** for plot title */
    private JCheckBox cbplottitle;
    private JTextField taplottitle;
    private JButton btntitlefont;

    /** for legend */
    private JCheckBox cblegend;
    private JComboBox cmboxlegend;
    private JTextField talegend;
    private JComboBox comboanchor;
    private JButton btnlegendfont;

    private XYPlot xyplot;
    private PiePlot pieplot;

    /** for anti-aliasing */
    private JCheckBox cbantialias;

    private JPanel thispanel;

    /** Creates a new instance of GeneralAttributes */
    public GeneralAttributes(PlotAttributesEditor parent) {
        super(parent);
        thispanel = this;
    }

    public boolean updateChart() {
        logger.debug("updating chart!");
        JFreeChart chart = parent.getGraphPanel().getChart();
        chart.setAntiAlias(cbantialias.isSelected());
        String title = "";
        if (cbplottitle.isSelected()) {
            title = taplottitle.getText();
            chart.getTitle().setFont(btntitlefont.getFont());
        } else {
            title = "";
        }
        chart.getTitle().setText(title);

        LegendItemSource lsource = null;
        if (xyplot != null) {
            int dsetCount = xyplot.getDatasetCount();
            int count = 0;
            for (int i = 0; i < dsetCount; i++) {
                XYSeriesCollection collection = (XYSeriesCollection) xyplot
                        .getDataset(i);
                int scount = collection.getSeriesCount();
                for (int j = 0; j < scount; j++) {
                    collection.getSeries(j).setKey(range[count]);
                    count++;
                }
            }
            lsource = xyplot;
        } else if (pieplot != null) {
            // DefaultPieDataset data = (DefaultPieDataset)
            // pieplot.getDataset();
            DefaultPieDataset old = (DefaultPieDataset) pieplot.getDataset();
            Number[] values = new Number[range.length];
            for (int i = 0; i < range.length; i++) {
                values[i] = old.getValue(i);
            }
            DefaultPieDataset data = new DefaultPieDataset();
            for (int i = 0; i < range.length; i++) {
                data.setValue(range[i], values[i]);
            }
            pieplot.setDataset(data);
            lsource = pieplot;
        }
        boolean blegend = cblegend.isSelected();
        chart.removeLegend();
        if (blegend) {
            LegendTitle ltitle = new LegendTitle(lsource);
            String legendanchor = comboanchor.getSelectedItem().toString();
            if (legendanchor.equals(stranchorpos[0])) {
                ltitle.setPosition(RectangleEdge.BOTTOM);
            } else if (legendanchor.equals(stranchorpos[1])) {
                ltitle.setPosition(RectangleEdge.TOP);
            } else if (legendanchor.equals(stranchorpos[2])) {
                ltitle.setPosition(RectangleEdge.RIGHT);
            } else if (legendanchor.equals(stranchorpos[3])) {
                ltitle.setPosition(RectangleEdge.LEFT);
            }
            chart.addLegend(ltitle);
        }

        return true;
    }

    public void init() {
        if (parent == null) {
            logger.debug("'parent' is null.");
            return;
        }
        Plot plot = parent.getSelectedPlot();
        if (plot == null) {
            logger.debug("'plot' is null.");
            return;
        }

        if (plot instanceof XYPlot) {
            xyplot = (XYPlot) plot;
        } else if (plot instanceof PiePlot) {
            pieplot = (PiePlot) plot;
        } else {
            return;
        }
    }

    private String[] range;

    private String[] stranchorpos = new String[] { "bottom", "top", "right",
            "left" };

    protected void initGUI() {
        removeAll();
        setLayout(new BorderLayout());

        JPanel p = new JPanel();
        p.setLayout(new GridBagLayout());
        GridBagConstraints constraints = new GridBagConstraints();
        constraints.gridx = 0;
        constraints.gridy = 0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.weightx = 1;
        constraints.weighty = 0;

        JPanel ptitle = new JPanel();
        ptitle.setLayout(new BoxLayout(ptitle, BoxLayout.X_AXIS));

        String title = parent.getGraphPanel().getChart().getTitle().getText();
        boolean titleEnabled = true;
        if (title == null || title.trim().length() == 0) {
            titleEnabled = false;
        }
        cbplottitle = new JCheckBox("show title");
        cbplottitle.setSelected(titleEnabled);
        taplottitle = new JTextField(25);
        btntitlefont = new JButton("select font");

        if (titleEnabled) {
            taplottitle.setText(title);
            btntitlefont.setFont(parent.getGraphPanel().getChart().getTitle()
                    .getFont());
        }

        ptitle.add(cbplottitle);
        ptitle.add(taplottitle);
        ptitle.add(btntitlefont);
        ptitle.setBorder(new TitledBorder("title"));
        p.add(ptitle, constraints);

        JPanel plegend = new JPanel();
        // plegend.setLayout(new BoxLayout(plegend, BoxLayout.X_AXIS));
        plegend.setLayout(new GridLayout(1, 5));

        cblegend = new JCheckBox("show legend");
        // LegendTitle legend = parent.getGraphPanel().getChart().getLegend();
        // if ( legend != null ) {
        // cblegend.setSelected(true);
        // RectangleAnchor anchor = legend.getLegendItemGraphicAnchor();
        // }

        Vector rangeVector = new Vector();
        if (xyplot != null) {
            int dsetCount = xyplot.getDatasetCount();
            for (int i = 0; i < dsetCount; i++) {
                XYSeriesCollection collection = (XYSeriesCollection) xyplot
                        .getDataset(i);
                int scount = collection.getSeriesCount();
                for (int j = 0; j < scount; j++) {
                    rangeVector.addElement(collection.getSeries(j).getKey()
                            .toString());
                }
            }
        } else if (pieplot != null) {
            DefaultPieDataset data = (DefaultPieDataset) pieplot.getDataset();
            java.util.List keys = data.getKeys();
            for (int i = 0; i < keys.size(); i++) {
                rangeVector.addElement(keys.get(i));
            }
        }

        if (rangeVector.size() != 0) {
            range = new String[rangeVector.size()];
            rangeVector.copyInto(range);
        } else {
            logger.error("could not obtain series!");
        }
        if (range != null) {
            cmboxlegend = new JComboBox(range);
            talegend = new JTextField(13);
            talegend.setText(cmboxlegend.getItemAt(0).toString());
        } else {
            cmboxlegend = new JComboBox();
            talegend = new JTextField(13);
        }

        JPanel panchor = new JPanel();
        comboanchor = new JComboBox(stranchorpos);
        panchor.setBorder(new TitledBorder("anchor position"));
        panchor.add(comboanchor);

        btnlegendfont = new JButton("select font");

        plegend.add(cblegend);
        plegend.add(cmboxlegend);
        plegend.add(talegend);
        plegend.add(comboanchor);
        plegend.add(btnlegendfont);
        plegend.setBorder(new TitledBorder("legend"));
        constraints.gridy = 1;
        p.add(plegend, constraints);

        JPanel panti = new JPanel();
        panti.setLayout(new BoxLayout(panti, BoxLayout.X_AXIS));
        panti.setBorder(new TitledBorder("anti-aliasing"));
        cbantialias = new JCheckBox("enable anti-aliasing");
        cbantialias.setSelected(parent.getGraphPanel().getChart()
                .getAntiAlias());
        panti.add(cbantialias);
        constraints.gridy = 2;
        p.add(panti, constraints);

        cmboxlegend.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                talegend.setText(range[cmboxlegend.getSelectedIndex()]);
            }
        });

        talegend.addCaretListener(new CaretListener() {
            public void caretUpdate(CaretEvent ce) {
                range[cmboxlegend.getSelectedIndex()] = talegend.getText()
                        .trim();
            }
        });

        btntitlefont.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Font font = FontChooser.chooseFont(btntitlefont.getFont(),
                        thispanel);
                btntitlefont.setFont(font);
            }
        });

        btnlegendfont.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Font font = FontChooser.chooseFont(btnlegendfont.getFont(),
                        thispanel);
                btnlegendfont.setFont(font);
            }
        });

        add(p, BorderLayout.NORTH);
    }

    public void plotChanged(Plot plot) {
        updateChart();
        init();
        initGUI();
        revalidate();
    }

}
