/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/06/30, 19:52
!  AUTHOR(S): KOGA, Junichiro
!  File : LightEditor.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.viewer.prefs;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
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.media.j3d.BranchGroup;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JColorChooser;
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.BaseJ3DPanel;
import ciss.phase_viewer.acviewer.scenegraphelements.LightObject;
import ciss.phase_viewer.mainpanel.InternalFrameChase;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * 光源の設定を行うためのGUI.
 * 
 * @author
 */
public class LightEditor extends InternalFrameChase {
    private Logger logger = Logger.getLogger(LightEditor.class.getName());
    private BaseJ3DPanel parent;
    private GlobalProperties gp = PropertiesManager
            .getGlobalProperties(PropertiesManager.PROPERTIES_ACV);

    /** Creates a new instance of LightEditor */
    public LightEditor(BaseJ3DPanel parent) {
        super("edit light source", true, true, true, true, new Dimension(625,
                520));
        this.parent = parent;
        parent.addDisposeOnExit(this);
        init();
        setVisible(true);
    }

    private Vector lightSourceEditors = new Vector();
    private int numlights = 5;

    private void init() {
        Container container = getContentPane();
        container.setLayout(new BorderLayout());

        JPanel peditors = new JPanel();
        peditors.setLayout(new BoxLayout(peditors, BoxLayout.Y_AXIS));
        for (int i = 0; i < numlights; i++) {
            LightSourceEditor editor = new LightSourceEditor(i);
            peditors.add(editor);
            lightSourceEditors.addElement(editor);
        }

        JPanel btns = new JPanel();
        btns.setLayout(new BoxLayout(btns, BoxLayout.X_AXIS));
        JButton save = new JButton("apply");
        JButton close = new JButton("close");
        btns.add(save);
        btns.add(close);
        JPanel b = new JPanel();
        b.add(btns);

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

        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                for (int i = 0; i < lightSourceEditors.size(); i++) {
                    ((LightSourceEditor) lightSourceEditors.elementAt(i))
                            .save();
                }
                gp.storeProperty();

                BranchGroup bg = parent.getRootBranch();
                for (int i = 0; i < bg.numChildren(); i++) {
                    if (bg.getChild(i) instanceof LightObject) {
                        ((LightObject) bg.getChild(i)).recreate();
                        return;
                    }
                }
            }
        });

        container.add(peditors, BorderLayout.CENTER);
        container.add(b, BorderLayout.SOUTH);
    }

    class LightSourceEditor extends JPanel {
        private String[] types = new String[] { "off", "point", "directional",
                "ambient" };
        private JComboBox type;
        private JTextField posx;
        private JTextField posy;
        private JTextField posz;
        private JTextField dirx;
        private JTextField diry;
        private JTextField dirz;
        private JButton color;
        private int ID;

        LightSourceEditor(int ID) {
            this.ID = ID;
            init();
        }

        private void init() {
            GridBagConstraints gc = new GridBagConstraints();
            gc.weightx = 1;
            gc.weighty = 0;
            gc.fill = GridBagConstraints.HORIZONTAL;
            gc.anchor = GridBagConstraints.CENTER;

            // type
            type = new JComboBox(types);
            JPanel ptype = new JPanel();
            ptype.setLayout(new GridBagLayout());
            ptype.setBorder(new TitledBorder("light " + String.valueOf(ID + 1)));
            ptype.add(type, gc);

            // position
            JPanel ppos = new JPanel();
            ppos.setLayout(new GridLayout(1, 3));
            ppos.setBorder(new TitledBorder("position"));
            posx = new JTextField(5);
            posy = new JTextField(5);
            posz = new JTextField(5);
            JPanel pposx = new JPanel();
            pposx.setBorder(new TitledBorder("x"));
            JPanel pposy = new JPanel();
            pposy.setBorder(new TitledBorder("y"));
            JPanel pposz = new JPanel();
            pposz.setBorder(new TitledBorder("z"));
            pposx.add(posx);
            pposy.add(posy);
            pposz.add(posz);
            ppos.add(pposx);
            ppos.add(pposy);
            ppos.add(pposz);

            // direction
            JPanel pdir = new JPanel();
            pdir.setLayout(new GridLayout(1, 3));
            pdir.setBorder(new TitledBorder("direction"));
            dirx = new JTextField(5);
            diry = new JTextField(5);
            dirz = new JTextField(5);
            JPanel pdirx = new JPanel();
            pdirx.setBorder(new TitledBorder("x"));
            JPanel pdiry = new JPanel();
            pdiry.setBorder(new TitledBorder("y"));
            JPanel pdirz = new JPanel();
            pdirz.setBorder(new TitledBorder("z"));
            pdirx.add(dirx);
            pdiry.add(diry);
            pdirz.add(dirz);
            pdir.add(pdirx);
            pdir.add(pdiry);
            pdir.add(pdirz);

            // color
            color = new JButton("color");
            JPanel pcolor = new JPanel();
            pcolor.setLayout(new GridBagLayout());
            pcolor.add(color, gc);

            setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
            add(ptype);
            add(ppos);
            add(pdir);
            add(pcolor);

            type.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    if (type.getSelectedItem().equals(types[0])) {
                        posx.setEnabled(false);
                        posy.setEnabled(false);
                        posz.setEnabled(false);
                        dirx.setEnabled(false);
                        diry.setEnabled(false);
                        dirz.setEnabled(false);
                        color.setEnabled(false);
                    } else if (type.getSelectedItem().equals(types[1])) {
                        posx.setEnabled(true);
                        posy.setEnabled(true);
                        posz.setEnabled(true);
                        dirx.setEnabled(false);
                        diry.setEnabled(false);
                        dirz.setEnabled(false);
                        color.setEnabled(true);
                    } else if (type.getSelectedItem().equals(types[2])) {
                        posx.setEnabled(false);
                        posy.setEnabled(false);
                        posz.setEnabled(false);
                        dirx.setEnabled(true);
                        diry.setEnabled(true);
                        dirz.setEnabled(true);
                        color.setEnabled(true);
                    } else if (type.getSelectedItem().equals(types[3])) {
                        posx.setEnabled(false);
                        posy.setEnabled(false);
                        posz.setEnabled(false);
                        dirx.setEnabled(false);
                        diry.setEnabled(false);
                        dirz.setEnabled(false);
                        color.setEnabled(true);
                    }
                }
            });

            setValue();
        }

        private void setValue() {
            String light_prefix = "light" + String.valueOf(ID + 1) + "_";
            try {
                String strtype = gp.getProperty(light_prefix + "type");
                type.setSelectedItem(strtype);
            } catch (Exception exc) {
            }

            try {
                String[] foo = gp.getProperty(light_prefix + "position").split(
                        ",");
                posx.setText(foo[0]);
                posy.setText(foo[1]);
                posz.setText(foo[2]);
            } catch (Exception exc) {
            }

            try {
                String[] foo = gp.getProperty(light_prefix + "direction")
                        .split(",");
                dirx.setText(foo[0]);
                diry.setText(foo[1]);
                dirz.setText(foo[2]);
            } catch (Exception exc) {
            }

            try {
                String[] co = gp.getProperty(light_prefix + "color").split(",");
                java.awt.Color col = new java.awt.Color(
                        Float.parseFloat(co[0]), Float.parseFloat(co[1]),
                        Float.parseFloat(co[2]));
                color.setBackground(col);
            } catch (Exception exc) {
            }

            color.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    JColorChooser colorchooser = new JColorChooser();
                    Color col = color.getBackground();
                    Color colo = colorchooser.showDialog(parent, "Choose", col);
                    if (colo != null) {
                        color.setBackground(colo);
                    }
                }
            });

        }

        void save() {
            String light_prefix = "light" + String.valueOf(ID + 1) + "_";
            gp.setProperty(light_prefix + "type", type.getSelectedItem()
                    .toString());
            try {
                String x = posx.getText().trim();
                String y = posy.getText().trim();
                String z = posz.getText().trim();
                gp.setProperty(light_prefix + "position", x + "," + y + "," + z);
            } catch (Exception exc) {
            }
            try {
                String x = dirx.getText().trim();
                String y = diry.getText().trim();
                String z = dirz.getText().trim();
                gp.setProperty(light_prefix + "direction", x + "," + y + ","
                        + z);
            } catch (Exception exc) {
            }
            java.awt.Color c = color.getBackground();
            String red = String.valueOf(((float) c.getRed()) / 255.f);
            String green = String.valueOf(((float) c.getGreen()) / 255.f);
            String blue = String.valueOf(((float) c.getBlue()) / 255.f);
            gp.setProperty(light_prefix + "color", red + "," + green + ","
                    + blue);
        }

    }
}
