/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/11/18, 13:35
!  AUTHOR(S): KOGA, Junichiro
!  File : PlotAttributesEditor.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.graph.plotattributes;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.border.TitledBorder;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;

import ciss.phase_viewer.graph.GraphPanel;
import ciss.phase_viewer.graph.dataset.PlotProperties;
import ciss.phase_viewer.jdom.XMLUtils;
import ciss.phase_viewer.main.PluginLoader;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * グラフの属性変更を変更するパネルの「枠」
 * 
 * @author
 */
public class PlotAttributesEditor extends InternalFrameChase {
    private static Logger logger = Logger.getLogger(PlotAttributesEditor.class
            .getName());

    private Vector editors = new Vector();
    private GraphPanel parent;

    private JTabbedPane tabbedPane;

    private static final String xmlpath = "/ciss/phase_viewer/graph/plotattributes/Editors.xml";

    private JComboBox plotSelector;

    /** Creates a new instance of PlotAttributes */
    public PlotAttributesEditor(GraphPanel parent) {
        super("edit plot attributes", true, true, true, true, new Dimension(
                512, 532));
        this.parent = parent;
        this.parent.addChildrenPanel(this);
        init();
    }

    /**
     * PlotAttributesSubEditorの配列を返す. この配列のオブジェクトによって色々グラフの属性を編集できる.
     * 
     * @return PlotAttributesSubEditorの配列
     */
    public PlotAttributesSubEditor[] getPlotAttributesSubEditor(
            PlotAttributesEditor parent) {
        int plottype = getGraphPanel().getPlotProperties().getPlotType();
        URL url = PlotAttributesEditor.class.getResource(xmlpath);
        Document doc = XMLUtils.getDocumentFromURL(url);
        Element root = doc.getRootElement();
        java.util.List list = root.getChildren("editor");
        Vector subs = new Vector();
        for (int i = 0; i < list.size(); i++) {
            Element editor = (Element) list.get(i);
            String name = editor.getChildTextTrim("name");
            String loadclass = editor.getChildTextTrim("loadclass");
            String strplottype = editor.getChildTextTrim("associated_plottype");
            String[] strplottypes = strplottype.split(",");
            int[] types = null;
            if (strplottypes != null && strplottypes.length != 0) {
                types = new int[strplottypes.length];
                for (int j = 0; j < strplottypes.length; j++) {
                    if (strplottypes[j].equals("PIE")) {
                        types[j] = PlotProperties.PIEPLOT;
                    } else if (strplottypes[j].equals("XY")) {
                        types[j] = PlotProperties.XYPLOT;
                    }
                }
            }

            boolean enable_this = false;
            if (types != null && types.length != 0) {
                for (int j = 0; j < types.length; j++) {
                    if (types[j] == plottype) {
                        enable_this = true;
                        break;
                    }
                }
            }

            if (enable_this) {
                PlotAttributesSubEditor edit = (PlotAttributesSubEditor) PluginLoader
                        .instantiate(loadclass, new Object[] { parent });
                edit.setAttributeName(name);
                subs.addElement(edit);
            }
        }

        if (subs.size() == 0) {
            return null;
        }
        PlotAttributesSubEditor[] editors = new PlotAttributesSubEditor[subs
                .size()];
        subs.copyInto(editors);

        return editors;
    }

    public Plot getSelectedPlot() {
        int index = plotSelector.getSelectedIndex();
        if (getGraphPanel().getPlotProperties().getPlotType() == PlotProperties.XYPLOT) {
            XYPlot plot = parent.getChart().getXYPlot();
            logger.debug("xyplot: " + plot);
            return ciss.phase_viewer.graph.utils.PlotUtils
                    .getXYPlotFromCombinedXYPlot(plot, index);
        } else if (getGraphPanel().getPlotProperties().getPlotType() == PlotProperties.PIEPLOT) {
            Plot plot = parent.getChart().getPlot();
            logger.debug("pieplot: " + plot);
            return plot;
        }
        return null;
    }

    private void choosePlot() {
        Plot plot = getSelectedPlot();
        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            PlotAttributesSubEditor sub = (PlotAttributesSubEditor) tabbedPane
                    .getComponentAt(i);
            sub.plotChanged(plot);
        }
    }

    private void init() {
        PlotProperties props = parent.getPlotProperties();
        // System.out.println("parent: "+parent+" editor: "+parent.getEditor());
        int count = props.getSubPlotCount();
        String[] plots = new String[count];
        for (int i = 0; i < count; i++) {
            plots[i] = props.getSubPlotPropertiesAt(i).getDataSetCollection()
                    .getName();
        }
        plotSelector = new JComboBox(plots);
        plotSelector.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                choosePlot();
            }
        });

        getContentPane().setLayout(new BorderLayout());
        tabbedPane = new JTabbedPane();

        JPanel contents = new JPanel();

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

        PlotAttributesSubEditor[] editors = getPlotAttributesSubEditor(this);
        for (int i = 0; i < editors.length; i++) {
            editors[i].init();
            editors[i].initGUI();
            tabbedPane.addTab(editors[i].getAttributeName(), editors[i]);
        }

        contents.add(tabbedPane, constraints);
        constraints.weighty = 1;
        contents.add(new JPanel());
        constraints.weighty = 0;

        JPanel btnpanel = new JPanel();
        // btnpanel.setLayout(new BoxLayout(btnpanel,BoxLayout.X_AXIS));
        JButton btnupdate = new JButton("update");
        JButton btnclose = new JButton("close");

        JPanel pselector = new JPanel();
        pselector.setBorder(new TitledBorder("select plot"));
        pselector.add(plotSelector);
        btnpanel.add(pselector);
        btnpanel.add(btnupdate);
        btnpanel.add(btnclose);

        constraints.gridy = 2;
        constraints.anchor = GridBagConstraints.CENTER;
        contents.add(btnpanel, constraints);

        btnclose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        btnupdate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                doUpdate();
            }
        });

        getContentPane().add(contents, BorderLayout.NORTH);
    }

    public GraphPanel getGraphPanel() {
        return parent;
    }

    private void doUpdate() {
        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            PlotAttributesSubEditor sub = (PlotAttributesSubEditor) tabbedPane
                    .getComponentAt(i);
            if (!sub.updateChart()) {
                logger.error("update from " + sub.getAttributeName()
                        + " panel failed.");
            }
        }
    }

}
