import java.awt.*;

public class Ball {
    private int x, y;        // center
    private int vX, vY;     // speed
    private final int radius;
    private final Image image;

    public Ball(int x, int y, int vX, int vY, int radius, Image image)
    {
        this.x = x;
        this.y = y;
        this.vX = vX;
        this.vY = vY;
        this.radius = radius;
        this.image = image;
    }

    public int getX()
    {
        return x;
    }

    public void moveToCenter(int width, int height)
    {
        x = width / 2;
        y = height / 2;
    }

    public boolean isMovingUp()
    {
        return vY < 0;
    }

    public void speedUp()
    {
        int increment = 5;
        vX = vX < 0 ? vX - increment : vX + increment;
        vY = vY < 0 ? vY - increment : vY + increment;
    }

    public boolean move(int height, Racket racket1, Racket racket2)
    {
        boolean rebound = false;

        // moves the ball
        x += vX;
        y += vY;

        // rebound with walls
        if (y - radius <= 0 || y + radius >= height) {
            vY = -vY;
            rebound = true;
        }

        // rebound with left racket
        Rectangle r1 = new Rectangle(x - radius, y - radius, 2 * radius, 2 * radius);
        Rectangle r2 = new Rectangle(racket1.x, racket1.y, racket1.width, racket1.height);
        if (r1.intersects(r2) && vX < 0) {
            vX = -vX;
            int d = (x - radius) - (racket1.x + racket1.width);
            x -= 2 * d;
            rebound = true;
        }

        // rebound with right racket
        r2 = new Rectangle(racket2.x, racket2.y, racket2.width, racket2.height);
        if (r1.intersects(r2) && vX > 0) {
            vX = -vX;
            int d = (x + 2 * radius) - racket2.x;
            x -= 2 * d;
            rebound = true;
        }

        return rebound;
    }

    public void draw(Graphics2D g2)
    {
        g2.drawImage(image, x - radius, y - radius, radius * 2, radius * 2, null);
    }
}
