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


#include "BountyClass.h"

// Sets default values
ABountyClass::ABountyClass()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

}

void ABountyClass::ActivateFirstCheckpoint()
{
	if (BountyCheckpoints.IsEmpty() || BountyCheckpoints[0] == nullptr) return;
	
	BountyCheckpoints[0]->Active = true;
	BountyCheckpoints[0]->CompletedCheckpoint.AddDynamic(this, &ABountyClass::IncrementBountyCheckpoint);
	CheckpointActivated.Broadcast(BountyCheckpoints[0]->GetCheckpointTip());
}

void ABountyClass::DeActivateFirstCheckpoint()
{
	if (BountyCheckpoints.IsEmpty() || BountyCheckpoints[0] == nullptr) return;

	BountyCheckpoints[0]->CompletedCheckpoint.RemoveDynamic(this, &ABountyClass::IncrementBountyCheckpoint);
	BountyCheckpoints[0]->Active = false;
	BountyCheckpoints[0]->DestroyWaypoint();
}

void ABountyClass::SpawnCheckpoints()
{
	// Spawn all checkpoints associated with this bounty and store them in order
	FActorSpawnParameters SpawnParameters;
	SpawnParameters.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	
	for(TSubclassOf<ACheckpointClass> CheckpointClass : CheckpointsToSpawn)
	{
		if (CheckpointClass == nullptr)
		{
			// An unassigned checkpoint class can lead to undefined behaviour, hence the fatal log
			UE_LOG(LogTemp, Fatal, TEXT("A checkpoint class wasn't set for %s"), *BountyTitle);
			return;
		}

		FVector Loc = CheckpointClass.GetDefaultObject()->GetCheckpointSpawnTransform().GetLocation();
		FRotator Rot = CheckpointClass.GetDefaultObject()->GetCheckpointSpawnTransform().GetRotation().Rotator();
		ACheckpointClass* SpawnedCheckpoint = Cast<ACheckpointClass>(GetWorld()->SpawnActor<AActor>(CheckpointClass, Loc, Rot, SpawnParameters));
		BountyCheckpoints.Add(SpawnedCheckpoint);
	}
}

void ABountyClass::IncrementBountyCheckpoint()
{
	if (BountyCheckpoints.IsEmpty() || BountyCheckpoints[0] == nullptr) return;
	
	// Destroy Actor and Shrink Array
	BountyCheckpoints[0]->Active = false;
	BountyCheckpoints[0]->Destroy();
	BountyCheckpoints.RemoveAt(0);

	ActivateFirstCheckpoint();
}

void ABountyClass::CollectRewards_Implementation()
{
	UE_LOG(LogTemp, Warning, TEXT("The player has gained $%d for completing the bounty!"), RewardMoney);
}




