// Copyright (c) 2023 Alex Diener. All rights reserved.

#include "gamemath/VectorConversions.h"
#include "PROJECT_NAME/Drawing.h"
#include "PROJECT_NAME/Globals.h"
#include "PROJECT_NAME/Shaders.h"

void drawRectOutline(Rect4f rect, float inset, Color4f color, VertexIO * vertexIO) {
	drawRect(RECT4f(rect.xMin,         rect.xMax,         rect.yMin,         rect.yMin + inset), color, vertexIO);
	drawRect(RECT4f(rect.xMin,         rect.xMax,         rect.yMax - inset, rect.yMax),         color, vertexIO);
	drawRect(RECT4f(rect.xMin,         rect.xMin + inset, rect.yMin + inset, rect.yMax - inset), color, vertexIO);
	drawRect(RECT4f(rect.xMax - inset, rect.xMax,         rect.yMin + inset, rect.yMax - inset), color, vertexIO);
}

static void getSpriteDrawBounds(SpriteID spriteID, unsigned int animationTime, bool loop, Vector2f position, Rect4f * outVertexBounds, Rect4f * outTextureBounds) {
	Sprite * sprite = SpriteCollection_getSprite(g_spriteCollection, spriteID);
	if (sprite == NULL) {
		return;
	}
	SpriteAnimationFrame * frame = Sprite_getFrameAtTime(sprite, animationTime, loop);
	ImageCollectionEntry * imageEntry = &g_imageCollection->images[frame->imageIndex];
	if (imageEntry == NULL) {
		return;
	}
	Rect4f textureBounds = imageEntry->atlasEntry;
	Vector2f spriteSize = VECTOR2f((textureBounds.xMax - textureBounds.xMin) * g_imageCollectionTexture->width, (textureBounds.yMax - textureBounds.yMin) * g_imageCollectionTexture->height);
	Vector2i spriteOffset = VECTOR2i(frame->offset.x - sprite->origin.x, frame->offset.y + (imageEntry->size.y - sprite->origin.y));
	*outVertexBounds = Rect4f_fromPositionAndSize(VECTOR2f(position.x + spriteOffset.x, position.y - spriteOffset.y), spriteSize);
	*outTextureBounds = textureBounds;
}

void drawSprite(SpriteID spriteID, unsigned int animationTime, bool loop, Vector2f position, Color4f color, VertexIO * vertexIO) {
	Rect4f vertexBounds, textureBounds;
	getSpriteDrawBounds(spriteID, animationTime, loop, position, &vertexBounds, &textureBounds);
	writeQuad2DMultitexture(vertexBounds, textureBounds, color, 1, vertexIO);
}
