package de.frajul.endlessroll.levels;

import org.simpleframework.xml.Attribute;

import de.frajul.endlessroll.data.Vector;

public class MoveComponent {

    @Attribute
    private float length;
    @Attribute
    private float rotation;
    @Attribute
    private float startOffset;
    @Attribute
    private float direction;
    @Attribute
    private float speed;
    @Attribute
    private boolean hasPlayerXSpeed;
    @Attribute
    private float triggerDistance;

    public final float TRANSITION_VALUE = 0.001f;
    private Vector position;
    private float triangleWidth;
    private float triangleHeight;

    public void init(Vector obstaclePosition) {
        double rotationRadians = Math.toRadians(getRotation());
        double invertRotationRadians = Math.toRadians(90 - getRotation());

        this.triangleWidth = (float) (length * Math.sin(rotationRadians));
        this.triangleHeight = (float) (length * Math.sin(invertRotationRadians));

        float x = obstaclePosition.getX();
        float y = obstaclePosition.getY();
        x -= startOffset * triangleWidth;
        y -= startOffset * triangleHeight;
        this.position = new Vector(x, y);
    }

    public float getLength() {
        return length;
    }

    public float getRotation() {
        return rotation;
    }

    public float getStartOffset() {
        return startOffset;
    }

    public float getDirection() {
        return direction;
    }

    public float getSpeed() {
        return speed;
    }

    public boolean isHasPlayerXSpeed() {
        return hasPlayerXSpeed;
    }

    public float getTriggerDistance() {
        return triggerDistance;
    }

    public void calcSpeedForPlayerSpeed(float playerSpeed) {
        float xSpeed = playerSpeed;
        speed = xSpeed / new Vector(triangleWidth, triangleHeight).normalize().getX();
        speed /= TRANSITION_VALUE;
    }

    public float getLeftmostPosition() {
        return triangleWidth >= 0 ? position.x : position.x + triangleWidth;
    }

    public Vector getMovementVector(float moveDirection) {
        return new Vector(triangleWidth, triangleHeight).normalize()
                .mul(moveDirection * getSpeed() * TRANSITION_VALUE);
    }

    public Vector getPositionForProgress(float progress) {
        return new Vector(position.x + triangleWidth * progress,
                position.y + triangleHeight * progress);
    }

}
