package netmatch.qtool;

import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.PLayer;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;

import java.awt.geom.Point2D;
import java.awt.*;

public class QCreateNodeHandler extends PBasicInputEventHandler {

  private QToolFrame frame;

  public QCreateNodeHandler(QToolFrame frame) {
    this.frame = frame;
  }

  private void showPopup(PInputEvent event) {
    Point2D pos = event.getPosition();
    int x = (int) pos.getX();
    int y = (int) pos.getY();

    QElement popupElement;

    if(event.getPickedNode() instanceof QText)
      popupElement = ((QText) event.getPickedNode()).getOwner();
    else if(!(event.getPickedNode() instanceof QElement))
      return;
    else
      popupElement = (QElement) event.getPickedNode();

    frame.popup.show((Component) event.getComponent(), x, y, popupElement);
  }

  public void mouseClicked(PInputEvent event) {
    if(event.isRightMouseButton()) {
      showPopup(event);
      return;
    }
    // only by left mouse-button click
    if(!event.isLeftMouseButton())
      return;

    // create new node as composition of ellipse and text
    PLayer nodeLayer = ((PCanvas) (event.getComponent())).getCamera().getLayer(1);
    Point2D pressPoint = event.getPosition();
    QNode node = new QNode((float) pressPoint.getX(), (float) pressPoint.getY(), "n" + Network.nodeCount++);
    node.addToLayer(nodeLayer);
    showInfo(event);
    frame.isModif = true;
    frame.setTitleModif();
    Network.nCount++;
    frame.updateStatus();
  }

  public void mouseMoved(PInputEvent event) {
    super.mouseMoved(event);
    showInfo(event);
  }

  private void showInfo(PInputEvent event) {
    QElement elem;
    if(event.getPickedNode() instanceof QText)
      elem = ((QText) event.getPickedNode()).getOwner();
    else if(event.getPickedNode() instanceof QElement)
      elem = (QElement) event.getPickedNode();
    else {
      frame.infoArea.setText("");
      return;
    }
    frame.infoArea.setText(elem.getInfo());
  }

}
