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


#include "DDIHealth.h"

// Sets default values for this component's properties
UDDIHealth::UDDIHealth()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;
	SetIsReplicatedByDefault(true);
	MaxHealth = 0;
	CurrentHealth = 0;
	ClassName = ClassNames::Scout;
	HealTickTime = 1.f;
	HealDelayTime = 2.f;
	
}

// Called when the game starts
void UDDIHealth::BeginPlay()
{
	Super::BeginPlay();

	FString classNameString = UEnum::GetValueAsName(ClassName).ToString();
	TArray<FString> ParsedStrings;

	// Split the string by the comma delimiter
	classNameString.ParseIntoArray(ParsedStrings, TEXT("::"), true);
    
	if (FHealthSegment* Segment = HealthSegmentTable->FindRow<FHealthSegment>(FName(ParsedStrings[1]), FString("HealthSegments")))
	{
		HealthSegments = Segment->SegmentList;
		FString output = "";
		for (int seg : Segment->SegmentList)
			output.Append(seg + ", ");
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, "");
	}

	for (int seg : HealthSegments)
		MaxHealth += seg;

	CurrentHealth = MaxHealth;
	GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Emerald, FString::Printf(TEXT("CurrentHealth: %d"), CurrentHealth));
}


// Called every frame
void UDDIHealth::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	if (CurrentHealth < MaxHealth && !HealTimer.IsValid())
	{
		GetWorld()->GetTimerManager().SetTimer(HealTimer, this, &UDDIHealth::Heal, HealTickTime, true, HealDelayTime);
		int tempHealthPool = 0;
		for (int seg : HealthSegments)
		{
			if (CurrentHealth >= tempHealthPool)
				tempHealthPool += seg;
		}
		MaxHealth = tempHealthPool;
	}
		
	
}

void UDDIHealth::Heal()
{
	if (CurrentHealth >= MaxHealth)
	{
		CurrentHealth = MaxHealth;
		GetWorld()->GetTimerManager().ClearTimer(HealTimer);
		return;
	}

	CurrentHealth += 1;
}


// Called to cause damage
void UDDIHealth::TakeDamage(int DamageValue)
{		
	GetWorld()->GetTimerManager().ClearTimer(HealTimer);

	CurrentHealth -= DamageValue;
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Cyan, FString::Printf(TEXT("Client Hit\nHealth: %d"), CurrentHealth));
	
}