/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/05/01, 19:40
!  AUTHOR(S): KOGA, Junichiro
!  File : MultipleAtomEditor.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.acviewer.scenegraphelements;

import java.awt.BorderLayout;
import java.awt.Dimension;
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 org.apache.log4j.Logger;

import ciss.phase_viewer.acviewer.CoordsViewerInterface;
import ciss.phase_viewer.acviewer.operations.BasicOperations;
import ciss.phase_viewer.acviewer.scenegraphelements.atom.AtomObject;
import ciss.phase_viewer.atomcoord.AtomCoords;
import ciss.phase_viewer.common.TaggedString;
import ciss.phase_viewer.inputinterface.inputinterfacetable.InputInterfaceTableColumns;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * 複数の原子をいっぺんに変更する.
 * 
 * @author
 */
public class MultipleAtomEditor extends InternalFrameChase {
    private Logger logger = Logger
            .getLogger(MultipleAtomEditor.class.getName());
    private CoordsViewerInterface parent;

    /** Creates a new instance of MultipleAtomEditor */
    public MultipleAtomEditor(CoordsViewerInterface parent) {
        super("edit multiple atoms", new Dimension(500, 400));
        this.parent = parent;
        getContentPane().setLayout(
                new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
        init();
    }

    private void init() {
        initTrans();
        initAttrEditors();
        createButtons();
        pack();
        setVisible(true);
    }

    private JButton btnapply;
    private JButton btnremoveAll;
    private JButton btnclose;

    private void createButtons() {
        JPanel pbtns = new JPanel();
        pbtns.setLayout(new BoxLayout(pbtns, BoxLayout.X_AXIS));
        btnapply = new JButton("apply");
        btnremoveAll = new JButton("remove selected");
        btnclose = new JButton("close");
        pbtns.add(btnapply);
        pbtns.add(btnremoveAll);
        pbtns.add(btnclose);

        btnapply.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                apply();
            }
        });

        btnremoveAll.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                doRemoveAll();
            }
        });

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

        getContentPane().add(pbtns);
    }

    private AtomObject[] selectedAtoms;
    private AtomCoords coords;

    private void apply() {
        BasicOperations bao = parent.getBasicOperations();
        bao.wait(true);
        double x = 0.d;
        double y = 0.d;
        double z = 0.d;

        try {
            x = Double.parseDouble(textx.getText());
            y = Double.parseDouble(texty.getText());
            z = Double.parseDouble(textz.getText());
        } catch (NumberFormatException nfe) {
            logger.error("enter double values.");
        } catch (NullPointerException npe) {
            logger.error("found invalid value at 'translation'");
        }
        bao.translateSelectedAtoms(x, y, z);

        String elem = "";
        String element = "element";
        String[] pos = new String[3];
        Vector auxvec = new Vector();

        for (int i = 0; i < attrEditors.size(); i++) {
            AttrEditor editor = (AttrEditor) attrEditors.elementAt(i);
            if (!editor.isSelected()) {
                continue;
            }
            String ident = editor.getIdent();
            if (ident.equals(element)) {
                elem = editor.getValue();
            } else {
                TaggedString aux = new TaggedString(ident, editor.getValue());
                auxvec.addElement(aux);
            }
        }
        bao.modifyAttributesOfSelectedAtoms(elem, auxvec);

        bao.doUpdate();
    }

    private void doRemoveAll() {
        BasicOperations bao = parent.getBasicOperations();
        bao.removeSelectedAtoms();
        dispose();
    }

    private JTextField textx;
    private JTextField texty;
    private JTextField textz;

    private void initTrans() {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.setBorder(new TitledBorder("translation"));

        JPanel px = new JPanel();
        px.setBorder(new TitledBorder("x"));
        textx = new JTextField(5);
        px.add(textx);
        textx.setText("0.0");

        JPanel py = new JPanel();
        py.setBorder(new TitledBorder("y"));
        texty = new JTextField(5);
        py.add(texty);
        texty.setText("0.0");

        JPanel pz = new JPanel();
        pz.setBorder(new TitledBorder("z"));
        textz = new JTextField(5);
        pz.add(textz);
        textz.setText("0.0");

        p.add(px);
        p.add(py);
        p.add(pz);

        getContentPane().add(p);
    }

    private Vector attrEditors = new Vector();

    private void initAttrEditors() {
        InputInterfaceTableColumns[] columns = parent.getData()
                .getTableColums();
        if (columns == null && columns.length == 0) {
            logger.error("invalid TableSpec file.");
            return;
        }
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.setBorder(new TitledBorder("attributes"));

        int editor_per_row = 4;
        int editor_count = 0;
        JPanel prow = null;
        for (int i = 0; i < columns.length; i++) {
            if (!columns[i].hasApplytoAll()) {
                continue;
            }
            if (editor_count % editor_per_row == 0) {
                prow = new JPanel();
                prow.setLayout(new GridLayout(1, editor_per_row));
                logger.debug("adding prow");
                p.add(prow);
                editor_count = 0;
            }

            AttrEditor attrEditor = new AttrEditor(columns[i]);
            prow.add(attrEditor);
            attrEditors.addElement(attrEditor);
            editor_count++;
        }
        getContentPane().add(p);
    }

    class AttrEditor extends JPanel {
        private InputInterfaceTableColumns column;
        private JTextField text;
        private JCheckBox check;
        private JComboBox box;
        private JCheckBox apply;

        AttrEditor(InputInterfaceTableColumns column) {
            this.column = column;
            init();
        }

        String getIdent() {
            return column.getName();
        }

        private void init() {
            setLayout(new BorderLayout());
            setBorder(new TitledBorder(column.getName()));
            apply = new JCheckBox();
            add(apply, BorderLayout.WEST);
            if (column.getCellEditor().equals(
                    InputInterfaceTableColumns.TEXT_FIELD)) {
                text = new JTextField(5);
                text.setEnabled(false);
                add(text, BorderLayout.EAST);
            } else if (column.getCellEditor().equals(
                    InputInterfaceTableColumns.CHECK_BOX)) {
                check = new JCheckBox(column.getName());
                check.setEnabled(false);
                add(check, BorderLayout.EAST);
            } else if (column.getCellEditor().equals(
                    InputInterfaceTableColumns.COMBO_BOX)) {
                box = new JComboBox(column.getChoices());
                box.setEnabled(false);
                add(box, BorderLayout.EAST);
            }

            apply.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    boolean val = apply.isSelected();
                    if (text != null) {
                        text.setEnabled(val);
                    }
                    if (check != null) {
                        check.setEnabled(val);
                    }
                    if (box != null) {
                        box.setEnabled(val);
                    }
                }
            });
        }

        boolean isSelected() {
            return apply.isSelected();
        }

        String getValue() {
            if (text != null) {
                return text.getText();
            }
            if (check != null) {
                return check.isSelected() ? "1" : "0";
            }
            if (box != null) {
                return box.getSelectedItem().toString();
            }
            return "";
        }

    }

}
