// Multiplayer By Caleb


#include "Widgets/ValueGauge.h"

#include "AbilitySystemComponent.h"
#include "Components/ProgressBar.h"
#include "Components/TextBlock.h"

void UValueGauge::NativePreConstruct()
{
	Super::NativePreConstruct();
	ProgressBar->SetFillColorAndOpacity(BarColor);
}

void UValueGauge::SetAndBoundToGameplayAttribute(UAbilitySystemComponent* AbilitySystemComponent,
                                                 const FGameplayAttribute& Attribute,
                                                 const FGameplayAttribute& MaxAttribute)
{
	if (AbilitySystemComponent)
	{
		bool bFound{false};
		const float Value{AbilitySystemComponent->GetGameplayAttributeValue(Attribute, bFound)};
		const float MaxValue{AbilitySystemComponent->GetGameplayAttributeValue(MaxAttribute, bFound)};
		if (bFound) SetValue(Value, MaxValue);
		AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(Attribute).AddUObject(
			this, &ThisClass::ValueChanged);
		AbilitySystemComponent->GetGameplayAttributeValueChangeDelegate(MaxAttribute).AddUObject(
			this, &ThisClass::MaxValueChanged);
	}
}

void UValueGauge::SetValue(float NewValue, float NewMaxValue)
{
	CachedValue = NewValue;
	CachedMaxValue = NewMaxValue;
	if (NewMaxValue == 0)
	{
		UE_LOG(LogTemp, Warning, TEXT("Value Gauge: %s, NewMaxValue can't be 0"), *GetName());
		return;
	}

	const float NewPercentage{NewValue / NewMaxValue};
	ProgressBar->SetPercent(NewPercentage);
	const auto FormatOps{FNumberFormattingOptions().SetMaximumFractionalDigits(0)};
	ValueText->SetText(FText::Format(
		FTextFormat::FromString("{0}/{1}"),
		FText::AsNumber(NewValue, &FormatOps),
		FText::AsNumber(NewMaxValue, &FormatOps)
	));
}

void UValueGauge::ValueChanged(const FOnAttributeChangeData& ChangedData)
{
	SetValue(ChangedData.NewValue, CachedMaxValue);
}

void UValueGauge::MaxValueChanged(const FOnAttributeChangeData& ChangedData)
{
	SetValue(CachedValue, ChangedData.NewValue);
}
