package netmatch.qtool;

import edu.umd.cs.piccolo.PCamera;
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 QCreateLoopHandler extends PBasicInputEventHandler {

  private QToolFrame frame;

  public QCreateLoopHandler(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);
  }

  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());
  }

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

  public void mouseClicked(PInputEvent e) {
    if(e.isRightMouseButton()) {
      showPopup(e);
      return;
    }
    if(!e.isLeftMouseButton())
      return;

    PCamera pCamera = ((PCanvas) (e.getComponent())).getCamera();
    PLayer edgeLayer = pCamera.getLayer(0);

    if(!(e.getPickedNode() instanceof QNode || e.getPickedNode() instanceof QText))
      return;

    QNode node;
    if(e.getPickedNode() instanceof QText)
      node = ((QText) e.getPickedNode()).getOwner();
    else
      node = (QNode) e.getPickedNode();
    QLoop loop = new QLoop(node, "l" + Network.loopCount++);
    frame.isModif = true;
    frame.setTitleModif();
    node.addLoop(loop);
    edgeLayer.addChild(loop);
    loop.update();
    showInfo(e);
    Network.lCount++;
    frame.updateStatus();
  }
}
