#include "component_sprite.h"

/* Returns sprite rectangle. */
void
component_sprite_rectangle_get(ComponentSprite* self, Rectangle* rectangle)
{
	vec2 size;
	vec2 difference;

	component_sprite_size_get(self, size);

	rectangle->x = (self->position[0] - (size[0] / 2)) + self->offset[0];
	rectangle->y = (self->position[1] - (size[1] / 2)) + self->offset[1];
	rectangle->w = size[0];
	rectangle->h = size[1];
}

/* Sets sprite component info, additionally given atlas rows/columns. */
void
component_sprite_atlas_init
(
	ComponentSprite* self, 
	Texture texture, 
	ivec2 frameSize,
	ivec2 atlasSize,
	vec2 size, 
	vec3 position
)
{
	atlas_init(&self->atlas, texture, frameSize, atlasSize);

	glm_vec2_copy((f32*)size, self->size);
	glm_vec3_copy((f32*)position, self->position);
}

/* Sets sprite component info. */
void
component_sprite_init
(
	ComponentSprite* self, 
	Texture texture, 
	vec2 size, 
	vec3 position
)
{
	ivec2 atlasSize;

	glm_ivec2_one(atlasSize);

	component_sprite_atlas_init
	(
		self, 
		texture, 
		texture.size,
		atlasSize,
		size,
		position
	);
}

/* Gets the true size of a sprite, accounting for scaling. */
void
component_sprite_size_get(ComponentSprite* self, vec2 size)
{
	glm_vec2_copy(self->size, size);

	size[0] *= self->scale[0];
	size[1] *= self->scale[1];
}

/* Ticks sprite component. */
void
component_sprite_add(ComponentSprite* self, ECS* ecs)
{
	glm_vec2_copy((f32*)COMPONENT_SPRITE_SCALE, self->scale);
	glm_vec4_copy((f32*)COMPONENT_SPRITE_COLOR, self->color);
}

/* Draws sprite component. */
void
component_sprite_draw(ComponentSprite* self, ECS* ecs)
{
	mat4 model;
	vec2 size;
	vec3 position;
	vec3 modelOrigin;

	component_sprite_size_get(self, size);
	
	glm_vec3_copy(self->position, position);

	glm_vec3_add(position, self->offset, position);

	position[0] -= size[0] / 2;
	position[1] -= size[1] / 2;

	glm_vec3_zero(modelOrigin);

	modelOrigin[0] = (size[0] / 2);
	modelOrigin[1] = (size[1] / 2);
	modelOrigin[2] = 0.0f;

	glm_mat4_identity(model);
	glm_translate(model, position);
	glm_rotate_at(model, modelOrigin, self->rotation, (f32*)COMPONENT_SPRITE_ROTATION_AXIS);

	texture_quad_draw
	(
		&ecs->game->renderer,
		&ecs->game->resources.shaders[SHADER_TEXTURE_QUAD],
		&self->atlas,
		model,
		size,
		self->color
	);
}
