#include "component_shop_item.h"

static void _shop_item_bought(ComponentShopItem* self, ECS* ecs);

/* Increases values associated with buying a shop item. */
static void
_shop_item_bought(ComponentShopItem* self, ECS* ecs)
{
	ComponentGoodies* goodies;
	ComponentGoodies* affectedGoodies;
	ComponentUpgrades* upgrades;
	ComponentHealth* health;

	goodies = ecs_component_get(ecs, ECS_COMPONENT_GOODIES, self->affectedID);

	if (goodies->value < self->price && self->type != SHOP_ITEM_FEED)
		return;

	switch (self->type)
	{
		case SHOP_ITEM_UPGRADE_LIFETIME:
			upgrades = ecs_component_get(ecs, ECS_COMPONENT_UPGRADES, self->affectedID);
			upgrades->currentLevels[UPGRADE_LIFETIME]++;
			break;
		case SHOP_ITEM_UPGRADE_AMMO:
			upgrades = ecs_component_get(ecs, ECS_COMPONENT_UPGRADES, self->affectedID);
			upgrades->currentLevels[UPGRADE_AMMO]++;
			break;
		case SHOP_ITEM_UPGRADE_REDIRECTS:
			upgrades = ecs_component_get(ecs, ECS_COMPONENT_UPGRADES, self->affectedID);
			upgrades->currentLevels[UPGRADE_REDIRECTS]++;
			break;
		case SHOP_ITEM_HEALTH:
			health = ecs_component_get(ecs, ECS_COMPONENT_HEALTH, self->affectedID);
			if (health->value >= health->max)
				return;
			health->value++;
			break;
		case SHOP_ITEM_FEED:
			affectedGoodies = ecs_component_get(ecs, ECS_COMPONENT_GOODIES, self->affectedID2);
			affectedGoodies->value += goodies->value;
			break;
		default:
			break;
	}

	self->isBought = false;

	if (self->type == SHOP_ITEM_FEED)
	{
		if (goodies->value > 0)
			sound_play(&ecs->game->resources.sounds[SOUND_GULP], SOUND_PRIORITY);
	
		goodies->value = 0;
		return;
	}
	else
		goodies->value -= self->price;

	self->purchaseCount++;

	self->price = pow(self->basePrice, self->exponent * self->purchaseCount);

	sound_play(&ecs->game->resources.sounds[SOUND_UPGRADE], SOUND_PRIORITY);
}

/* Sets shop_item component info. */
void
component_shop_item_init(ComponentShopItem* self, ShopItemType type, u32 price, f32 exponent, u32 affectedID, u32 affectedID2)
{
	self->basePrice = price;
	self->price = self->basePrice;
	self->exponent = exponent;
	self->type = type;
	self->affectedID = affectedID;
	self->affectedID2 = affectedID2;
}

/* Ticks shop item component. */
void
component_shop_item_tick(ComponentShopItem* self, ECS* ecs)
{
	if (self->isBought)
		_shop_item_bought(self, ecs);
}
