package depart.commun.monde2d;

import ca.ntro.app.Ntro;
import ca.ntro.app.fx.controls.World2dMouseEventFx;
import ca.ntro.app.world2d.Object2dFx;
import depart.frontal.evenements.EvtChangerCurseur;
import javafx.scene.Cursor;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.ArcType;

public class Balle2d extends Object2dFx {
	
	private static final double CONST_A = 900;
	private static final double CONST_B = 0.8;
	
	private MondeDepart2d monde2d;
	
	private boolean attrA;
	private double offsetX;
	private double offsetY;
	
	public Balle2d(MondeDepart2d monde2d) {
		super();

		setWidth(75);           
		setHeight(75);
		
		setAccelerationY(CONST_A);
		
		this.monde2d = monde2d;
	}

	@Override
	public void onAddedToWorld() {
		setTopLeftX(getWorldWidth() / 2 - getWidth() / 2);
		setTopLeftY(10);
	}

	@Override
	protected boolean onMouseEvent(World2dMouseEventFx mouseEvent) {
		if(mouseEvent.mouseEventFx().getEventType().equals(MouseEvent.MOUSE_PRESSED)
				&& mouseEvent.mouseEventFx().getButton().equals(MouseButton.PRIMARY)) {
			
			offsetX = mouseEvent.worldX() - getTopLeftX();
			offsetY = mouseEvent.worldY() - getTopLeftY();
			
			monde2d.agripperBalle(this);
			
			attrA = true;
			
			setSpeedY(0);
			setAccelerationY(0);
			
			Ntro.newEvent(EvtChangerCurseur.class)
			    .setCurseur(Cursor.HAND)
			    .trigger();
			
			return true;
		}


		return false;
	}
	
	@Override
	public void onTimePasses(double secondsElapsed) {
		super.onTimePasses(secondsElapsed);

		if(attrA) return;

		if(getTopLeftY() + getHeight() > getWorldHeight()) {

			setTopLeftY(getWorldHeight()-getHeight());
			setSpeedY(-1 * Math.abs(getSpeedY()) * CONST_B); 
		}
	}

	@Override
	public void drawOnWorld(GraphicsContext gc) {
		gc.setFill(Color.BROWN);

		gc.fillArc(getTopLeftX(),
				   getTopLeftY(),
				   getWidth(),
				   getHeight(),
				   0,
				   360,
				   ArcType.CHORD);
	}

	public void suivreSouris(double worldX, 
			                 double worldY) {
		
		setTopLeftX(worldX - offsetX); 
		setTopLeftY(worldY - offsetY); 
	}

	public void relacher() {
		attrA = false;
		setAccelerationY(CONST_A);
	}

}
