#include "ball.h"

Ball::Ball()
{
    ballImage = load_image("ball.png");
	angle = PI;
	vel = 1;
	x = SCREENWIDTH / 2 - ballImage->w / 2;
	y = SCREENHEIGHT / 2 - ballImage->h / 2;
    xVel = MOVEMENT * vel * cos(angle);
    yVel = MOVEMENT * vel * sin(angle);
}

int Ball::getY()
{
    return (int)y;
}

void Ball::reset()
{
    if (angle > PI/2 && angle <= PI + PI/2)
        angle = 0;
    else
        angle = PI;
    if (vel >= 1.6)
        vel -= .6;
	x = SCREENWIDTH / 2 - ballImage->w / 2;
	y = SCREENHEIGHT / 2 - ballImage->h / 2;
	xVel = MOVEMENT * vel * cos(angle);
    yVel = MOVEMENT * vel * sin(angle);
}

int Ball::move(const Paddle &player1, const Paddle &player2, Uint32 deltaTicks)
{
    if ((x >= player1.getX() && x <= player1.getX() + player1.getW() && y + ballImage->h / 2 >= player1.getY() && y - ballImage->h / 2 + ballImage->h <= player1.getY() + player1.getH()))
    {
        angle = atan((int)((player1.getY() + player1.getH() / 2) - (y + ballImage->h / 2)) / sqrt((ELLIPSEA*ELLIPSEA) * (1 - (((int)((player1.getY() + player1.getH() / 2) - (y + ballImage->h / 2)) * (int)((player1.getY() + player1.getH() / 2) - (y + ballImage->h / 2))) / (ELLIPSEB * ELLIPSEB)))));
        if (vel < MAXBALLVEL)
            vel += .2;
        xVel = MOVEMENT * vel * cos(angle);
        yVel = MOVEMENT * vel * sin(angle);
    }
    else if ((x + ballImage->w >= player2.getX() && x + ballImage->w <= player2.getX() + player2.getW() && y + ballImage->h / 2 >= player2.getY() && y - ballImage->h / 2 + ballImage->h <= player2.getY() + player2.getH()))
    {
        angle = atan((int)((player2.getY() + player2.getH() / 2) - (y + ballImage->h / 2)) / sqrt((ELLIPSEA*ELLIPSEA) * (1 - (((int)((player2.getY() + player2.getH() / 2) - (y + ballImage->h / 2)) * (int)((player2.getY() + player2.getH() / 2) - (y + ballImage->h / 2))) / (ELLIPSEB * ELLIPSEB)))));
        angle = PI - angle;
        if (vel < MAXBALLVEL)
            vel += .2;
        xVel = MOVEMENT * vel * cos(angle);
        yVel = MOVEMENT * vel * sin(angle);
    }
    if (y - yVel * (deltaTicks / 1000.f) < SCREENOFFSET || y - yVel * (deltaTicks / 1000.f) + ballImage->h > SCREENHEIGHT - SCREENOFFSET)
    {
        angle = 2 * PI - angle;
        xVel = MOVEMENT * vel * cos(angle);
        yVel = MOVEMENT * vel * sin(angle);
    }
    x += xVel * (deltaTicks / 1000.f);
    y -= yVel * (deltaTicks / 1000.f);
    if (x + ballImage->w <= 0)
    {
        reset();
        return 2;
    }
    else if (x >= SCREENWIDTH)
    {
        reset();
        return 1;
    }
    else
        return 0;
}

void Ball::draw() const
{
    SDL_Rect offset;
    offset.x = (int)x;
    offset.y = (int)y;
    SDL_BlitSurface(ballImage, NULL, screen, &offset);
}
