// Fill out your copyright notice in the Description page of Project Settings.


#include "SurvivalStatsWidget.h"

#include "Components/ProgressBar.h"
#include "FpsPlayer.h"
#include "GameFramework/PlayerController.h"
#include "SurvivalStatsComponent.h"

void USurvivalStatsWidget::NativeConstruct()
{
	Super::NativeConstruct();

	// Releve des couleurs telles que reglees dans le Designer, avant que le
	// code ne commence a les remplacer.
	if (HealthBar)
	{
		HealthBaseColor = HealthBar->GetFillColorAndOpacity();
	}
	if (HungerBar)
	{
		HungerBaseColor = HungerBar->GetFillColorAndOpacity();
	}
	if (ThirstBar)
	{
		ThirstBaseColor = ThirstBar->GetFillColorAndOpacity();
	}

	BindToOwningPawn();
}

void USurvivalStatsWidget::BindToOwningPawn()
{
	USurvivalStatsComponent* NewStats = ResolveStats();
	if (BoundStats.Get() == NewStats)
	{
		return;
	}

	if (BoundStats.IsValid())
	{
		BoundStats->OnStatsChanged.RemoveDynamic(this, &USurvivalStatsWidget::HandleStatsChanged);
	}

	BoundStats = NewStats;

	if (BoundStats.IsValid())
	{
		BoundStats->OnStatsChanged.AddDynamic(this, &USurvivalStatsWidget::HandleStatsChanged);
	}
	else
	{
		UE_LOG(LogTemp, Warning, TEXT("USurvivalStatsWidget : aucun USurvivalStatsComponent trouve sur le pawn possede."));
	}

	Refresh();
}

void USurvivalStatsWidget::NativeDestruct()
{
	if (BoundStats.IsValid())
	{
		BoundStats->OnStatsChanged.RemoveDynamic(this, &USurvivalStatsWidget::HandleStatsChanged);
	}
	BoundStats.Reset();

	Super::NativeDestruct();
}

USurvivalStatsComponent* USurvivalStatsWidget::ResolveStats() const
{
	const APlayerController* OwningController = GetOwningPlayer();
	AFpsPlayer* Player = OwningController ? Cast<AFpsPlayer>(OwningController->GetPawn()) : nullptr;
	return Player ? Player->GetSurvivalStats() : nullptr;
}

void USurvivalStatsWidget::HandleStatsChanged()
{
	Refresh();
}

void USurvivalStatsWidget::Refresh()
{
	if (!BoundStats.IsValid())
	{
		return;
	}

	ApplyBar(HealthBar, BoundStats->GetHealthPercent(), HealthBaseColor);
	ApplyBar(HungerBar, BoundStats->GetHungerPercent(), HungerBaseColor);
	ApplyBar(ThirstBar, BoundStats->GetThirstPercent(), ThirstBaseColor);
}

void USurvivalStatsWidget::ApplyBar(UProgressBar* Bar, float Percent, const FLinearColor& BaseColor) const
{
	if (!Bar)
	{
		return;
	}

	Bar->SetPercent(FMath::Clamp(Percent, 0.f, 1.f));
	Bar->SetFillColorAndOpacity(Percent <= CriticalThreshold ? CriticalColor : BaseColor);
}
