#include "CharacterClassComponent.hpp"
#include "CharacterClassDatabase.hpp"

int CharacterClassComponent::getStat(const Ogre::String &name) const
{
	const auto *def = CharacterClassDatabase::getSingleton().findStat(name);
	if (!def)
		return 0;

	if (def->kind == CharacterClassDatabase::StatKind::ResourcePool) {
		// For pools, getStat returns the CURRENT value
		return getPoolCurrent(name);
	}

	// For attributes, return the stored value clamped to min/max
	auto it = stats.find(name);
	if (it == stats.end())
		return 0;
	if (it->second < def->minValue)
		return def->minValue;
	if (it->second > def->maxValue)
		return def->maxValue;
	return it->second;
}

int CharacterClassComponent::getPoolMax(const Ogre::String &name) const
{
	const auto *def = CharacterClassDatabase::getSingleton().findStat(name);
	if (!def || def->kind != CharacterClassDatabase::StatKind::ResourcePool)
		return 0;
	auto it = stats.find(name);
	if (it == stats.end())
		return 0;
	if (it->second < def->minValue)
		return def->minValue;
	if (it->second > def->maxValue)
		return def->maxValue;
	return it->second;
}

int CharacterClassComponent::getPoolCurrent(const Ogre::String &name) const
{
	int maxVal = getPoolMax(name);
	if (maxVal <= 0)
		return 0;
	auto it = currentPools.find(name);
	if (it == currentPools.end())
		return maxVal; // not initialized yet, assume full
	if (it->second < 0)
		return 0;
	if (it->second > maxVal)
		return maxVal;
	return it->second;
}

void CharacterClassComponent::setPoolCurrent(const Ogre::String &name,
						     int value)
{
	int maxVal = getPoolMax(name);
	if (maxVal <= 0)
		return;
	if (value < 0)
		value = 0;
	if (value > maxVal)
		value = maxVal;
	currentPools[name] = value;
}

int CharacterClassComponent::getSkill(const Ogre::String &name) const
{
	auto it = skills.find(name);
	if (it == skills.end())
		return 0;
	const auto *def = CharacterClassDatabase::getSingleton().findSkill(name);
	if (!def)
		return it->second;
	if (it->second < 0)
		return 0;
	if (it->second > def->maxValue)
		return def->maxValue;
	return it->second;
}

int CharacterClassComponent::getNeed(const Ogre::String &name) const
{
	auto it = needs.find(name);
	if (it == needs.end())
		return 0;
	const auto *def = CharacterClassDatabase::getSingleton().findNeed(name);
	if (!def)
		return it->second;
	if (it->second < 0)
		return 0;
	if (it->second > def->maxValue)
		return def->maxValue;
	return it->second;
}
