#include "ItemInstance.h"

#include "ItemDefinition.h"
#include "StructUtils/InstancedStruct.h"
#include "NakedDesire/SaveGame/ItemSaveRecord.h"

void UItemInstance::PostInitProperties()
{
	Super::PostInitProperties();

	if (HasAnyFlags(RF_ClassDefaultObject | RF_ArchetypeObject | RF_NeedLoad))
		return;
	if (!InstanceId.IsValid())
		InstanceId = FGuid::NewGuid();
}

void UItemInstance::PostDuplicate(EDuplicateMode::Type DuplicateMode)
{
	Super::PostDuplicate(DuplicateMode);
	InstanceId = FGuid::NewGuid();
}

void UItemInstance::SetInstanceId(FGuid InId)
{
	InstanceId = InId;
}

FItemSaveRecord UItemInstance::ToSaveRecord() const
{
	FItemSaveRecord Record;
	Record.InstanceId = InstanceId;
	Record.Definition = ItemDefinition;
	CaptureState(Record.State);
	return Record;
}

UItemInstance* UItemInstance::CreateFromRecord(UObject* Outer, const FItemSaveRecord& Record)
{
	UItemDefinition* Definition = Record.Definition.LoadSynchronous();
	if (!Definition)
	{
		UE_LOG(LogTemp, Warning, TEXT("UItemInstance::CreateFromRecord: failed to load definition for instance %s"),
			*Record.InstanceId.ToString());
		return nullptr;
	}

	const TSubclassOf<UItemInstance> InstanceClass = Definition->GetInstanceClass();
	if (!InstanceClass)
	{
		UE_LOG(LogTemp, Warning, TEXT("UItemInstance::CreateFromRecord: %s returned no instance class"),
			*Definition->GetName());
		return nullptr;
	}

	UItemInstance* Instance = NewObject<UItemInstance>(Outer, InstanceClass);
	Instance->ItemDefinition = Definition;
	Instance->InstanceId = Record.InstanceId.IsValid() ? Record.InstanceId : FGuid::NewGuid();
	Instance->ApplyState(Record.State);
	return Instance;
}