package pl.shockah.ts.entities;

import java.util.List;
import pl.shockah.Util;
import pl.shockah.glib.geom.vector.Vector2d;
import pl.shockah.glib.logic.standard.Entities;
import pl.shockah.glib.logic.standard.EntityBase;
import pl.shockah.glib.logic.standard.EntityCollidable;
import pl.shockah.ts.entities.waterblur.WaterBlur;
import pl.shockah.ts.gameplay.Game;

public class EntityBoxGravity extends EntityBox implements IGravity {
	public Vector2d toMove = new Vector2d(), vel = new Vector2d();
	
	protected double getYAcceleration(boolean water) {return .5d*(water ? 2f/3f : 1f);}
	protected double getYVelocityLimit() {return 12d;}
	
	protected void onUpdate() {
		List<EntityCollidable> platforms = Util.getAllOf(getPlatforms(),EntityCollidable.class);
		boolean collidesD = collidesAt(platforms,pos.x,pos.y+1);
		boolean inWater = WaterBlur.isInWater(this);
		
		if (!collidesD) {
			double fallSpeed = getYAcceleration(inWater), limit = getYVelocityLimit();
			if (vel.y < limit) vel.y += fallSpeed;
			if (vel.y > limit) {
				vel.y -= fallSpeed;
				if (vel.y < limit) vel.y = limit;
			}
		}
		
		toMove.add(new Vector2d(inWater ? vel.x/4d : vel.x,inWater ? vel.y/4d : vel.y).scale(Game.me.time.getSpeed(this)));
		while (true) {
			boolean v = false;
			
			if (toMove.y >= .5d || toMove.y < -.5d) {
				v = true;
				int sign2 = (int)Math.signum(toMove.y);
				if (!collidesAt(platforms,pos.x,pos.y+sign2)) {
					pos.y += sign2;
					toMove.y -= sign2;
				} else {
					toMove.y = 0;
					vel.y = 0;
				}
			}
			
			if (!v) break;
		}
	}
	protected List<EntityBase> getPlatforms() {
		return Entities.getTypes(EntityWall.class,EntityBox.class);
	}
}