#include "component_shop_button.h"

static void _button_init(ComponentShopButton* self, ECS* ecs, vec3 position);

/* Initializes the button aspect. */
static void
_button_init(ComponentShopButton* self, ECS* ecs, vec3 position)
{
	ComponentButton* button;
	ComponentSprite* sprite;
	ComponentShopItem* shopItem;

	button = ecs_component_get(ecs, ECS_COMPONENT_BUTTON, self->component.id);
	shopItem = ecs_component_get(ecs, ECS_COMPONENT_SHOP_ITEM, self->shopItemID);

	component_button_init
	(
		button,
		ecs,
		ecs->game->resources.textures[TEXTURE_ICONS],
		(s32*)ICON_FRAME_SIZE,
		(s32*)ICON_ATLAS_SIZE,
		(f32*)SHOP_BUTTON_SIZE,
		position
	);

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

	switch (shopItem->type)
	{
		case SHOP_ITEM_UPGRADE_LIFETIME:
			sprite->atlas.index = ICON_SHOP_LIFETIME;
			break;
		case SHOP_ITEM_UPGRADE_REDIRECTS:
			sprite->atlas.index = ICON_SHOP_REDIRECTS;
			break;
		case SHOP_ITEM_UPGRADE_AMMO:
			sprite->atlas.index = ICON_SHOP_AMMO;
			break;
		case SHOP_ITEM_HEALTH:
			sprite->atlas.index = ICON_SHOP_HEALTH;
			break;
		case SHOP_ITEM_FEED:
			sprite->atlas.index = ICON_SHOP_ELEMENTAL;
			break;
		default:
			break;
	}

	sprite->position[2] += SHOP_BUTTON_SPRITE_Z_OFFSET;
}

/* Initializes a button component. */
void
component_shop_button_init
(
	ComponentShopButton* self, 
	ECS* ecs,
	vec3 position,
	u32 shopItemID
)
{
	self->streakID = ecs_entity_add(ecs);
	self->shopItemID = shopItemID;

	_button_init(self, ecs, position);

	entity_streak_square_init
	(
		ecs,
		self->streakID,
		position,
		(f32*)SHOP_BUTTON_STREAK_SIZE
	);
}

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

/* Runs on a button component being added. */
void 
component_shop_button_delete(ComponentShopButton* self, ECS* ecs)
{
	ecs_component_delete(ecs, ECS_COMPONENT_BUTTON, self->component.id);

	ecs_entity_delete(ecs, self->streakID);
}

/* Ticks button component. */
void 
component_shop_button_tick(ComponentShopButton* self, ECS* ecs)
{
	ComponentButton* button;

	button = ecs_component_get(ecs, ECS_COMPONENT_BUTTON, self->component.id);

	if (button->state == BUTTON_PRESSED)
	{
		ComponentShopItem* shopItem;

		shopItem = ecs_component_get(ecs, ECS_COMPONENT_SHOP_ITEM, self->shopItemID);
		
		shopItem->isBought = true;
	}
}
