// Copyright Pacificao. All Rights Reserved.

#include "AgrarianPersistentActorComponent.h"
#include "AgrarianPersistentStateProvider.h"

UAgrarianPersistentActorComponent::UAgrarianPersistentActorComponent()
{
	PrimaryComponentTick.bCanEverTick = false;
}

bool UAgrarianPersistentActorComponent::IsSaveable() const
{
	return ActorTypeId != NAME_None && GetOwner() != nullptr;
}

FAgrarianSavedWorldActor UAgrarianPersistentActorComponent::CaptureSaveState() const
{
	if (const AActor* Owner = GetOwner(); Owner && Owner->Implements<UAgrarianPersistentStateProvider>())
	{
		IAgrarianPersistentStateProvider::Execute_CapturePersistentState(
			const_cast<AActor*>(Owner),
			const_cast<UAgrarianPersistentActorComponent*>(this));
	}

	FAgrarianSavedWorldActor SavedActor;
	SavedActor.ActorTypeId = ActorTypeId;
	SavedActor.StringState = StringState;
	SavedActor.NumberState = NumberState;

	if (bSaveTransform && GetOwner())
	{
		SavedActor.Transform = GetOwner()->GetActorTransform();
	}

	return SavedActor;
}

void UAgrarianPersistentActorComponent::ApplySaveState(const FAgrarianSavedWorldActor& SavedActor)
{
	StringState = SavedActor.StringState;
	NumberState = SavedActor.NumberState;

	if (ActorTypeId == NAME_None)
	{
		ActorTypeId = SavedActor.ActorTypeId;
	}

	if (bSaveTransform && GetOwner())
	{
		GetOwner()->SetActorTransform(SavedActor.Transform);
	}

	if (AActor* Owner = GetOwner(); Owner && Owner->Implements<UAgrarianPersistentStateProvider>())
	{
		IAgrarianPersistentStateProvider::Execute_ApplyPersistentState(Owner, this);
	}
}
