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

import java.awt.AWTEvent;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.util.Enumeration;

import javax.media.j3d.Bounds;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.Shape3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.WakeupCriterion;
import javax.media.j3d.WakeupOnAWTEvent;
import javax.media.j3d.WakeupOr;

import org.apache.log4j.Logger;

import ciss.phase_viewer.acviewer.MainPanel;
import ciss.phase_viewer.acviewer.scenegraphelements.MultipleAtomEditor;
import ciss.phase_viewer.acviewer.scenegraphelements.TGAtom;

import com.sun.j3d.utils.geometry.Primitive;
import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.PickTool;
import com.sun.j3d.utils.picking.behaviors.PickMouseBehavior;

public class AtomPicker extends PickMouseBehavior {
    private static Logger logger = Logger.getLogger(AtomPicker.class.getName());

    private Atom atom;
    private AtomObject atomObject;

    private WakeupCriterion[] mouseEvents;
    private WakeupOr mouseCriterion;

    private PickTool picker;

    // int pickMode = PickTool.BOUNDS;
    int pickMode = PickTool.GEOMETRY;

    private Canvas3D canvas;

    private TransformGroup parent;

    private boolean button1Press = false;

    public AtomPicker(Canvas3D canvas, BranchGroup root, Bounds bounds,
            Atom atom) {
        super(canvas, root, bounds);
        this.atom = atom;
        this.atomObject = atom.getAtomObject();

        this.setSchedulingBounds(bounds);
        pickCanvas.setMode(pickMode);

        this.canvas = canvas;
    }

    public AtomPicker(Canvas3D canvas, BranchGroup root, Bounds bounds) {
        super(canvas, root, bounds);
        this.setSchedulingBounds(bounds);
        pickCanvas.setMode(pickMode);

        this.canvas = canvas;
    }

    public void processStimulus(Enumeration criteria) {
        WakeupCriterion wakeup;
        AWTEvent[] evt = null;
        int xpos = 0, ypos = 0;

        while (criteria.hasMoreElements()) {
            wakeup = (WakeupCriterion) criteria.nextElement();
            if (wakeup instanceof WakeupOnAWTEvent)
                evt = ((WakeupOnAWTEvent) wakeup).getAWTEvent();
        }

        if (evt == null) {
            return;
        }

        if (evt[0] instanceof MouseEvent) {
            mevent = (MouseEvent) evt[0];
            processMouseEvent((MouseEvent) evt[0]);
            xpos = mevent.getPoint().x;
            ypos = mevent.getPoint().y;
        }

        if (buttonPress) {
            if (!update(xpos, ypos)) {
                ((AtomSelectionCanvas) parent).deselectAll();
            }
        }

        if (button1Press) {
            bootAtomAtributeEditPanel(xpos, ypos);
        }
        wakeupOn(wakeupCondition);
    }

    private void processMouseEvent(MouseEvent evt) {
        buttonPress = false;
        button1Press = false;
        if (evt.getButton() == MouseEvent.BUTTON2
                || (evt.getButton() == MouseEvent.BUTTON1 && evt.isAltDown())) {
            if (evt.getID() == MouseEvent.MOUSE_PRESSED
                    || evt.getID() == MouseEvent.MOUSE_CLICKED) {
                buttonPress = true;
                return;
            } else if (evt.getID() == MouseEvent.MOUSE_MOVED) {
                buttonPress = true;
                return;
            }
        } else if (evt.getButton() == MouseEvent.BUTTON1 && (!evt.isAltDown())) {
            button1Press = true;
            return;
        }
    }

    public void updateScene(int xpos, int ypos) {
    }

    private boolean update(int xpos, int ypos) {
        if (pickCanvas == null)
            return false;
        pickCanvas.setShapeLocation(xpos, ypos);
        if (pickCanvas == null)
            return false;
        PickResult[] result = pickCanvas.pickAllSorted();
        if (result == null) {
            logger.debug("AtomPicker returned null.");
            return false;
        }
        for (int i = 0; i < result.length; i++) {
            Primitive pri = (Primitive) result[i].getNode(PickResult.PRIMITIVE);
            if (pri != null && pri instanceof AtomSphere) {
                AtomObject obj = ((AtomSphere) pri).getAtomObject();
                boolean b = obj.toggleSelected();
                if (b)
                    logger.info("selected atom " + obj.getID());
                else
                    logger.info("deselected atom " + obj.getID());
                logger.debug(obj);
                return true;
            }
            Shape3D s3d = (Shape3D) result[i].getNode(PickResult.SHAPE3D);
            if (s3d != null && s3d instanceof AtomFilledCircle) {
                AtomObject obj = ((AtomFilledCircle) s3d).getAtomObject();
                boolean b = obj.toggleSelected();
                if (b)
                    logger.info("selected atom " + obj.getID());
                else
                    logger.info("deselected atom " + obj.getID());
                logger.debug(obj);
                return true;
            }
        }
        return false;
    }

    private void bootAtomAtributeEditPanel(int xpos, int ypos) {
        if (pickCanvas == null)
            return;
        pickCanvas.setShapeLocation(xpos, ypos);
        if (pickCanvas == null)
            return;
        PickResult[] result = pickCanvas.pickAllSorted();
        if (result == null) {
            logger.debug("AtomPicker returned null.");
            return;
        }

        int numSelected = ((TGAtom) parent).getSelectedAtomCount();
        for (int i = 0; i < result.length; i++) {
            Primitive pri = (Primitive) result[i].getNode(PickResult.PRIMITIVE);
            if (pri != null && pri instanceof AtomSphere) {
                AtomObject obj = ((AtomSphere) pri).getAtomObject();
                if (obj.isSelected()) {
                    if (numSelected == 1) {
                        logger.debug("booting atom atribute edit panel ...");
                        bootAtomEditor(Integer.parseInt(obj.getID()));
                    } else if (numSelected > 1) {
                        // ACVMultipleAtomEditor edi = new
                        // ACVMultipleAtomEditor(((TGAtom)
                        // parent).getParentFrame());
                        // ((TGAtom)
                        // parent).getParentFrame().addDisposeOnExit(edi);
                        MultipleAtomEditor edit = new MultipleAtomEditor(
                                ((TGAtom) parent).getParentFrame());
                        ((TGAtom) parent).getParentFrame().addDisposeOnExit(
                                edit);
                        return;
                    }
                }
            }
            Shape3D s3d = (Shape3D) result[i].getNode(PickResult.SHAPE3D);
            if (s3d != null && s3d instanceof AtomFilledCircle) {
                AtomObject obj = ((AtomFilledCircle) s3d).getAtomObject();
                if (obj.isSelected()) {
                    if (numSelected == 1) {
                        logger.debug("booting atom atribute edit panel ...");
                        bootAtomEditor(Integer.parseInt(obj.getID()));
                    } else if (numSelected > 1) {
                        // ACVMultipleAtomEditor edi = new
                        // ACVMultipleAtomEditor(((TGAtom)
                        // parent).getParentFrame());
                        // ((TGAtom)
                        // parent).getParentFrame().addDisposeOnExit(edi);
                        MultipleAtomEditor edit = new MultipleAtomEditor(
                                ((TGAtom) parent).getParentFrame());
                        ((TGAtom) parent).getParentFrame().addDisposeOnExit(
                                edit);
                        return;
                    }
                }
            }
        }

    }

    private void bootAtomEditor(int id) {
        TGAtom tgatom = (TGAtom) parent;
        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(((TGAtom) mp.getRootTransform())
                .getBasicOperations());
        // editor.addAtomListener(this);
        // editor.revalidate();
        mp.addDisposeOnExit(editor);
        editor.revalidate();
    }

    public void setParent(TransformGroup parent) {
        this.parent = parent;
    }

}
