/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : ElementList.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.projectmanipulator.phase.preparationpanel.atomconfig;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.table.TableColumn;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.ElementInfo;
import ciss.phase_viewer.inputinterface.InputInterface;
import ciss.phase_viewer.primitiveguis.ChoicePanelPhase;
import ciss.phase_viewer.primitiveguis.InputPanelPhase;
import ciss.phase_viewer.primitiveguis.PhaseInputChildrenPanel;
import ciss.phase_viewer.primitiveguis.tableforinputinterface.TableForInputInterface;

public class ElementList extends PhaseInputChildrenPanel {

    private static Logger logger = Logger
            .getLogger(ElementList.class.getName());

    private ElementInfo eI;

    private String[] elements_list;
    private String[] atomic_num_list;
    private JComboBox combo_elm;
    private JComboBox combo_num;

    private TableForInputInterface tbl_elm;

    private ChoicePanelPhase cppelm;

    private ChoicePanelPhase cppatnum;
    private InputPanelPhase ippmass;

    public ElementList(InputInterface inputInterface) {
        super("Element List", true, true, true, true, inputInterface,
                new Dimension(500, 450));
    }

    public void createGUI() {
        Container cont = getContentPane();
        cont.setLayout(new BoxLayout(cont, BoxLayout.Y_AXIS));
        cont.add(createElementListPanel());
        setResizable(true);
    }

    public void delete() {
    }

    public void add() {
    }

    public void save() {
    }

    private JPanel createElementListPanel() {

        // define elements_list
        eI = ElementInfo.getElementInfo();
        int num_elements = eI.num_elements;
        elements_list = new String[num_elements - 1];
        atomic_num_list = new String[num_elements - 1];

        for (int i = 1; i < num_elements; i++) {
            elements_list[i - 1] = eI.getSymbolFromNumber(i);
            atomic_num_list[i - 1] = Integer.toString(i);
            logger.debug("got symbol: " + eI.getSymbolFromNumber(i)
                    + " whose atomic number is: " + i);
        }

        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));

        String[] elmSpec = { "structure.element_list" };
        String[] colname_elm = { "element", "atomicnumber", "mass", "zeta",
                "deviation" };

        tbl_elm = new TableForInputInterface(elmSpec, inputInterface, this);
        tbl_elm.setColumnSelectionAllowed(true);
        tbl_elm.setRowSelectionAllowed(true);

        setEditorForElementTable();

        JScrollPane scrPane = new JScrollPane();
        scrPane.getViewport().setView(tbl_elm.getPanel());
        scrPane.setPreferredSize(new Dimension(450, 200));

        p.add(scrPane);
        //
        // JPanel p_element_new = new JPanel();
        // // p_element_new.setLayout(new
        // BoxLayout(p_element_new,BoxLayout.Y_AXIS));
        //
        // // p_element_new.setLayout(new GridLayout(2, 3, 1, 1));
        //
        // JPanel p_upper_row = new JPanel();
        // p_upper_row.setLayout(new GridLayout(1,3));
        //
        // JPanel p_lower_row = new JPanel();
        // p_lower_row.setLayout(new GridLayout(1,3));
        //
        // String[] dummy = {""};
        // cppelm = new
        // ChoicePanelPhase(dummy,inputInterface,"element",elements_list);
        // cppatnum = new
        // ChoicePanelPhase(dummy,inputInterface,"atomic number",atomic_num_list);
        // ippmass = new
        // InputPanelPhase(dummy,inputInterface,"mass",InputPanelPhase.NONE,7);
        //
        // p_upper_row.add(cppelm);
        // p_upper_row.add(cppatnum);
        // p_upper_row.add(ippmass);
        //
        // InputPanelPhase ippzeta = new
        // InputPanelPhase(dummy,inputInterface,"zeta",InputPanelPhase.NONE,7);
        // InputPanelPhase ippdev = new
        // InputPanelPhase(dummy,inputInterface,"deviation",InputPanelPhase.NONE,7);
        //
        // p_lower_row.add(ippzeta);
        // p_lower_row.add(ippdev);
        // p_lower_row.add(new JPanel());
        //
        // p_element_new.add(p_upper_row);
        // p_element_new.add(p_lower_row);
        //
        // //add listeners (manually)
        // cppelm.getComboBox().addActionListener( new ActionListener() {
        // public void actionPerformed(ActionEvent e) {
        // String symbol = (String) cppelm.getComboBox().getSelectedItem();
        // String number = String.valueOf(eI.getNumberFromSymbol(symbol));
        // String mass = eI.getMassFromSymbol(symbol);
        // cppatnum.getComboBox().setSelectedItem(number);
        // ippmass.getTextField().setText(mass);
        // }
        // });
        //
        // cppatnum.getComboBox().addActionListener( new ActionListener() {
        // public void actionPerformed(ActionEvent e) {
        // String number = (String) cppatnum.getComboBox().getSelectedItem();
        // String symbol = eI.getSymbolFromNumber(Integer.parseInt(number));
        // String mass = eI.getMassFromNumber(Integer.parseInt(number));
        // cppelm.getComboBox().setSelectedItem(symbol);
        // ippmass.getTextField().setText(mass);
        // }
        // });
        //
        // cppelm.getComboBox().setSelectedItem("H");
        //
        // p.add(p_element_new);
        //
        // PhaseInputPanelInterface[] guis =
        // {cppelm,cppatnum,ippmass,ippzeta,ippdev};
        // AddButton addButton = new AddButton(tbl_elm, guis, this);
        // DeleteButton deleteButton = new DeleteButton(tbl_elm, this);
        //
        // JPanel p_elmbtn = new JPanel();
        // p_elmbtn.setLayout(new BoxLayout(p_elmbtn, BoxLayout.X_AXIS));
        //
        // p_elmbtn.add(addButton);
        // p_elmbtn.add(deleteButton);
        // p_elmbtn.add(new CloseButton(this));
        //
        // p.add(p_elmbtn);
        // // p.add(Box.createVerticalStrut(5));
        //
        // p.add(p_elmbtn);
        //
        // p.add(Box.createVerticalStrut(5));

        return p;
    }

    private void setEditorForElementTable() {

        TableColumn column_elm = tbl_elm.getColumnModel().getColumn(0);
        combo_elm = new JComboBox(elements_list);
        column_elm.setCellEditor(new DefaultCellEditor(combo_elm));

        TableColumn column_num = tbl_elm.getColumnModel().getColumn(1);
        combo_num = new JComboBox(atomic_num_list);
        column_num.setCellEditor(new DefaultCellEditor(combo_num));

        combo_elm.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                String symbolSelected = (String) combo_elm.getSelectedItem();

                int row = tbl_elm.getSelectedRow();
                if (row >= 0) {
                    if (combo_elm.isPopupVisible()) {
                        try {
                            tbl_elm.setValueAt(String.valueOf(eI
                                    .getNumberFromSymbol(symbolSelected)), row,
                                    1);
                            tbl_elm.setValueAt(
                                    eI.getMassFromSymbol(symbolSelected), row,
                                    2);
                        } catch (Exception ee) {
                            System.out
                                    .println("failed to obtain number and mass from symbol");
                            ee.printStackTrace();
                        }
                    }
                }

                updateTable();
            }
        });

        combo_num.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                String numberSelected = (String) combo_num.getSelectedItem();
                int row = tbl_elm.getSelectedRow();
                if (row >= 0) {
                    if (combo_num.isPopupVisible()) {
                        try {
                            tbl_elm.setValueAt(eI.getSymbolFromNumber(Integer
                                    .parseInt(numberSelected)), row, 0);
                            tbl_elm.setValueAt(eI.getMassFromNumber(Integer
                                    .parseInt(numberSelected)), row, 2);
                        } catch (Exception ee) {
                            System.out
                                    .println("failed to obtain symbol and mass from atomic number");
                        }
                    }
                }
                updateTable();
            }
        });

    }

    private void updateTable() {
        tbl_elm.update(tbl_elm.getGraphics());
    }

}
