/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/09/05, 11:25
!  AUTHOR(S): KOGA, Junichiro
!  File : EditKeyListener.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.keylistener;

import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.media.j3d.Transform3D;
import javax.vecmath.Vector3d;

import org.apache.log4j.Logger;

import ciss.phase_viewer.acviewer.CoordsViewerInterface;
import ciss.phase_viewer.acviewer.J3DPanel;
import ciss.phase_viewer.acviewer.MainPanel;
import ciss.phase_viewer.acviewer.scenegraphelements.MultipleAtomEditor;
import ciss.phase_viewer.acviewer.scenegraphelements.TGAtom;
import ciss.phase_viewer.acviewer.scenegraphelements.atom.ACVAtomEditor;
import ciss.phase_viewer.acviewer.scenegraphelements.atom.AtomObject;
import ciss.phase_viewer.settings.GlobalProperties;
import ciss.phase_viewer.settings.PropertiesListener;
import ciss.phase_viewer.settings.PropertiesManager;

/**
 * 「編集」操作用のキーリスナー
 * 
 * @author
 */
public class EditKeyListener implements KeyListener, PropertiesListener {
    private Logger logger = Logger.getLogger(EditKeyListener.class.getName());
    private TGAtom tgatom;
    private J3DPanel panel;

    private double transx = 0;
    private double transy = 0;

    private GlobalProperties props = PropertiesManager
            .getGlobalProperties(PropertiesManager.PROPERTIES_ACV);

    /** Creates a new instance of EditKeyListener */
    public EditKeyListener(J3DPanel panel) {
        if (panel instanceof MainPanel)
            this.tgatom = (TGAtom) panel.getRootTransform();
        this.panel = panel;
        try {
            transx = Double.parseDouble(props
                    .getProperty("keylistener_atomtrans_x"));
            transy = Double.parseDouble(props
                    .getProperty("keylistener_atomtrans_y"));
        } catch (Exception exc) {
        }
        PropertiesManager.getGlobalProperties(PropertiesManager.PROPERTIES_ACV)
                .addPropertiesListener(this);
    }

    public void keyTyped(KeyEvent e) {
    }

    public void keyReleased(KeyEvent e) {
    }

    public void keyPressed(KeyEvent e) {
        if (tgatom == null)
            return;
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            if (tgatom.getSelectedAtomCount() == 0)
                return;
            AtomObject[] atoms = tgatom.getSelectedAtoms();
            int numSelected = atoms.length;
            if (numSelected == 1) {
                logger.debug("booting atom atribute edit panel ...");
                bootAtomEditor(Integer.parseInt(atoms[0].getID()));
            } else if (numSelected > 1) {
                // ACVMultipleAtomEditor edi = new
                // ACVMultipleAtomEditor(((TGAtom) parent).getParentFrame());
                // ((TGAtom) parent).getParentFrame().addDisposeOnExit(edi);
                MultipleAtomEditor edit = new MultipleAtomEditor(
                        tgatom.getParentFrame());
                tgatom.getParentFrame().addDisposeOnExit(edit);
                return;
            }
        }

        if (e.getKeyCode() == KeyEvent.VK_Z && e.isControlDown()) {
            CoordsViewerInterface mp = (CoordsViewerInterface) panel;
            mp.getCD().getAtomCoords().saveState();
            if (mp.getCD().getAtomCoords().getAtomList().undo()) {
                mp.getCD().setCoords(mp.getCD().getAtomCoords());
            }
            mp.getCD().getAtomCoords().finalizeState();
        }

        if (e.getKeyCode() == KeyEvent.VK_Y && e.isControlDown()) {
            CoordsViewerInterface mp = (CoordsViewerInterface) panel;
            mp.getCD().getAtomCoords().saveState();
            if (mp.getCD().getAtomCoords().getAtomList().redo()) {
                mp.getCD().setCoords(mp.getCD().getAtomCoords());
            }
            mp.getCD().getAtomCoords().finalizeState();
        }

        if (e.getKeyCode() == KeyEvent.VK_DELETE) {
            CoordsViewerInterface mp = (CoordsViewerInterface) panel;
            mp.getBasicOperations().removeSelectedAtoms();
        }

        if (e.isAltDown()) {
            if (e.getKeyCode() == KeyEvent.VK_UP
                    || e.getKeyCode() == KeyEvent.VK_K) {
                translate(0, 1);
            } else if (e.getKeyCode() == KeyEvent.VK_DOWN
                    || e.getKeyCode() == KeyEvent.VK_J) {
                translate(0, -1);
            } else if (e.getKeyCode() == KeyEvent.VK_LEFT
                    || e.getKeyCode() == KeyEvent.VK_H) {
                translate(-1, 0);
            } else if (e.getKeyCode() == KeyEvent.VK_RIGHT
                    || e.getKeyCode() == KeyEvent.VK_L) {
                translate(1, 0);
            }
        }
    }

    private void translate(int x, int y) {
        double trax = transx * x;
        double tray = transy * y;
        Vector3d p3d = new Vector3d(trax, tray, 0d);
        Transform3D foo = new Transform3D();
        ((MainPanel) panel).getRootTransform().getTransform(foo);
        foo.invert();
        foo.transform(p3d);
        ((CoordsViewerInterface) panel).getBasicOperations()
                .translateSelectedAtoms(p3d.x, p3d.y, p3d.z);
    }

    private void bootAtomEditor(int id) {
        MainPanel mp = tgatom.getParentFrame();
        ciss.phase_viewer.atomcoord.Atom atom = mp.getCD().getAtomCoords()
                .getAtomList().getAtomAt(id - 1);
        logger.debug(atom);
        ACVAtomEditor editor = new ACVAtomEditor(mp.getData().getTableColums(),
                atom, false, id - 1, "edit attributes for atom no. "
                        + new Integer(id), new Dimension(400, 250),
                ciss.phase_viewer.mainpanel.InternalFrameChase.EAST, mp);
        editor.addAtomListener(mp.getBasicOperations());
        mp.addDisposeOnExit(editor);
    }

    public void propertiesStored(GlobalProperties properties) {
        try {
            transx = Double.parseDouble(properties
                    .getProperty("keylistener_atomtrans_x"));
            transy = Double.parseDouble(properties
                    .getProperty("keylistener_atomtrans_y"));
        } catch (Exception exc) {
        }
    }
}
