#include "component_button.h"

/* Sets the color of the button based on the state. */
static void
_component_button_color_set(ComponentButton* self, ECS* ecs)
{
	ComponentSprite* sprite;

	sprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->component.id);

	switch (self->state)
	{
		case BUTTON_PRESSED:
			glm_vec4_copy((f32*)COMPONENT_BUTTON_COLOR_PRESSED, sprite->color);
			break;
		case BUTTON_HOVER:
			glm_vec4_copy((f32*)COMPONENT_BUTTON_COLOR_HOVER, sprite->color);
			break;
		case BUTTON_UNSELECTED:
		default:
			glm_vec4_copy((f32*)COMPONENT_BUTTON_COLOR_UNSELECTED, sprite->color);
			break;
	}
}

/* Initializes a button component. */
void
component_button_init
(
	ComponentButton* self, 
	ECS* ecs,
	Texture texture,
	ivec2 frameSize,
	ivec2 atlasSize,
	vec2 size,
	vec3 position
)
{
	ComponentSprite* sprite;

	sprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->component.id);

	component_sprite_atlas_init
	(
		sprite,
		texture,
		frameSize,
		atlasSize,
		size,
		position
	);
}

/* Runs on a button component being added. */
void 
component_button_add(ComponentButton* self, ECS* ecs)
{
	ecs_component_add(ecs, ECS_COMPONENT_SPRITE, self->component.id);
}


/* Runs on a button component being added. */
void 
component_button_delete(ComponentButton* self, ECS* ecs)
{
	ecs_component_delete(ecs, ECS_COMPONENT_SPRITE, self->component.id);

}

/* Ticks button component. */
void 
component_button_tick(ComponentButton* self, ECS* ecs)
{
	ComponentSprite* sprite;
	vec2 mousePosition;
	SDL_FRect rectangle;

	sprite = ecs_component_get(ecs, ECS_COMPONENT_SPRITE, self->component.id);

	mouse_world_position_get(&ecs->game->input.mouse, &ecs->game->renderer, mousePosition);
	component_sprite_rectangle_get(sprite, &rectangle);

	if (rectangle_has_point(&rectangle, mousePosition))
	{
		self->state = BUTTON_HOVER;

		if (input_press(&ecs->game->input, INPUT_SELECT))
			self->state = BUTTON_PRESSED;
	}
	else
		self->state = BUTTON_UNSELECTED;

	_component_button_color_set(self, ecs);
}
