#include "Flipper.h"
#include "agk.h"

const float Flipper::ROTATION_SPEED = 720.0f;
const float Flipper::BASE_ROTATION = 50.0f;
const float Flipper::MAX_ROTATION = 80.0f;

Flipper::Flipper(unsigned int image, float x, float y, bool mirror)
{
	sprite = agk::CreateSprite(image);
	agk::SetSpriteOffset(sprite, 13.0f, 13.0f);
	agk::SetSpritePositionByOffset(sprite, x, y);
	agk::SetSpriteAngle(sprite, mirror ? BASE_ROTATION : -BASE_ROTATION);
	agk::SetSpriteFlip(sprite, mirror ? 1 : 0, 0);
	agk::SetSpritePhysicsOn(sprite, 3);
	agk::SetSpritePhysicsRestitution(sprite, 0.8f);
	agk::SetSpriteShape(sprite, 3);

	rotation_direction = mirror ? 1.0f : -1.0f;
	active = false;
}

void Flipper::activate()
{
	active = true;
}

void Flipper::desactivate()
{
	active = false;
}

void Flipper::update() {
	float const max_rotation_this_frame = agk::GetFrameTime() * ROTATION_SPEED;
	float const current_angle = agk::GetSpriteAngle(sprite) * rotation_direction;

	if (active) 
	{
		float max_rotate = BASE_ROTATION + MAX_ROTATION;
		if (max_rotate != current_angle) 
		{
			float const angle_after_move = current_angle + max_rotation_this_frame;
			float const new_angle = angle_after_move < max_rotate ? angle_after_move : max_rotate;
			agk::SetSpriteAngle(sprite, new_angle * rotation_direction);
		}
	}
	else 
	{
		if (BASE_ROTATION != current_angle) 
		{
			float const angle_after_move = current_angle - max_rotation_this_frame;
			float const new_angle = angle_after_move > BASE_ROTATION ? angle_after_move : BASE_ROTATION;
			agk::SetSpriteAngle(sprite, new_angle * rotation_direction);
		}
	}
}