package depart.commun.monde2d;

import ca.ntro.app.Ntro;
import ca.ntro.app.fx.controls.World2dMouseEventFx;
import ca.ntro.app.world2d.Object2dFx;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.effect.InnerShadow;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
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.5;
	private static final double CONST_C = 1.0;
	
	private double  attrA = CONST_C;
	private boolean attrB = false;

    private transient InnerShadow innerShadow = new InnerShadow();

	private transient Media sonPoc   = new Media(Balle2d.class.getResource("/sons/poc.wav").toString());
	private transient Media sonRampe = new Media(Balle2d.class.getResource("/sons/rampe.wav").toString());
	private transient Media sonSwish = new Media(Balle2d.class.getResource("/sons/swish.wav").toString());

	public Balle2d() {
		super();
		
		setWidth(60);           
		setHeight(60);

		setAccelerationY(CONST_A);
	}

	@Override
	public void onAddedToWorld() {
		setTopLeftX(getWorldWidth() / 2 - getWidth() / 2);
		setTopLeftY(getWorldHeight() - getHeight());
		
		attrA = CONST_C;
		attrB = true;
	}

	@Override
	protected boolean onMouseEvent(World2dMouseEventFx mouseEvent) {
		return false;
	}
	
	@Override
	public void onTimePasses(double secondsElapsed) {
		super.onTimePasses(secondsElapsed);

		if(getTopLeftY() + getHeight() > getWorldHeight()) {
			
			setTopLeftY(getWorldHeight()-getHeight());
			setSpeedY(-1 * Math.abs(getSpeedY()) * CONST_B); 

			if(Math.abs(getSpeedY()) < 45) {
				
				if(!attrB) {
					attrA = CONST_C;
					attrB = true;
					new MediaPlayer(sonRampe).play();
				}


			}else {

				new MediaPlayer(sonPoc).play();

			}
		}
		
		if(attrB) {

			attrA -= secondsElapsed;
			
			if(attrA <= 0) {
				
				attrA = CONST_C;
				attrB = false;
				setSpeedY(-1 * (500 + Ntro.random().nextDouble(150)));
				new MediaPlayer(sonSwish).play();
			}
		}
	}

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

		if(attrA > 0) {
			innerShadow.setOffsetY(getHeight() * attrA / CONST_C);
			innerShadow.setColor(Color.DARKBLUE);
			gc.setEffect(innerShadow);
		}
		
		double varA = (getTopLeftY()+getHeight()) / getWorldHeight();
		double varB = getWidth() * varA;
		double varC = getHeight() * varA;

		gc.fillArc(getTopLeftX() + getWidth()/2 - varB/2,
				   getTopLeftY() + getHeight()/2 - varC/2,
				   varB,
				   varC,
				   0,
				   360,
				   ArcType.CHORD);
	}

}
