package de.frajul.endlessroll.entities.tools;

import de.frajul.endlessroll.data.Vector;
import de.frajul.endlessroll.entities.Player;
import de.frajul.endlessroll.entities.collision.geometry.Geometry;
import de.frajul.endlessroll.entities.collision.geometry.Triangle;
import de.frajul.endlessroll.main.game.Timer;

/**
 * Created by Julian on 29.11.2015.
 */
public class Ramp extends Tool {

    public Ramp(Vector position) {
        super(ToolType.RAMP, position, .4f, .35f, true, true);
        animation.setLooping(true);
    }

    public float getGradient() {
        return super.getHeight() / super.getWidth();
    }

    public float getHeightAt(float x, boolean clamp) {
        float ratio = (x - getLeftEdge()) / super.getWidth();
        if (clamp) {
            if (ratio < 0)
                return getBottomEdge();
            if (ratio > 1)
                return getTopEdge();
        }
        return getBottomEdge() + super.getHeight() * ratio;
    }

    @Override
    public void onPlayerCollision(Player player, Timer timer) {
        float necessaryY = calcNecessaryPlayerY(player);
        player.getPosition().y = necessaryY;
        float acceleration = player.getMovement().x * getGradient();

        player.setGravityForce(0);
        player.getMovement().setY(0);
        player.addForce(acceleration);
    }

    private float calcNecessaryPlayerY(Player player) {
        float normalM = -1 / getGradient();
        Vector normalToCircleCenter = new Vector(-1, -normalM).normalize();
        normalToCircleCenter.mul(player.RADIUS);
        float normalX = player.getPosition().x - normalToCircleCenter.x;
        float normalY = getHeightAt(normalX, false);
        return normalY + normalToCircleCenter.y;
    }

    @Override
    protected Geometry createWorldCollisionBounds() {
        return new Triangle(this);
    }

    @Override
    protected Geometry createPlayerCollisionBounds() {
        return new Triangle(this);
    }

}
