#include "MyScoreComponent.h"

#include "Debug/PulseDebugTimeline.h"
#include "Engine/World.h"
#include "GameFramework/Actor.h"
#include "TimerManager.h"

void UMyScoreComponent::BeginPlay()
{
	Super::BeginPlay();

	// Tell the debugger that this component can describe itself. Does nothing in shipping builds.
	Pulse::Debug::RegisterSnapshotProvider(this);

	GetWorld()->GetTimerManager().SetTimer(AwardTimer, this, &UMyScoreComponent::AwardPoints, AwardInterval, true);
}

void UMyScoreComponent::EndPlay(const EEndPlayReason::Type InReason)
{
	if (UWorld* world = GetWorld())
		world->GetTimerManager().ClearTimer(AwardTimer);

	Pulse::Debug::UnregisterSnapshotProvider(this);
	Super::EndPlay(InReason);
}

void UMyScoreComponent::AddScore(int32 InPoints)
{
	Score += InPoints;

	// Source MyGame, category Score. The text is only built while the timeline records.
	PULSE_DEBUG_EVENT(this, MyGame, Score, Info, TEXT("%s scored %d points (total %d)"), *GetNameSafe(GetOwner()), InPoints, Score);
}

void UMyScoreComponent::AwardPoints()
{
	AddScore(PointsPerAward);
}

void UMyScoreComponent::GatherDebugSnapshot(FPulseDebugSnapshot& OutSnapshot) const
{
	FPulseDebugSnapshotSection& section = OutSnapshot.AddSection(TEXT("Score"));
	section.Add(TEXT("Owner"), GetNameSafe(GetOwner()));
	section.Add(TEXT("Score"), Score);
	section.Add(TEXT("Points per award"), PointsPerAward);

	// Warnings and errors colour the row and count in the badge of the Overview page.
	if (Score >= 100)
		section.AddWarning(TEXT("High score"), TEXT("The score is above 100"));
}
