// Copyright CodeSpartan, 2023. All rights reserved.
#include "AsyncLoadPersistentClass.h"
#include "Engine/AssetManager.h"
#include "JsonObjectWrapper.h"
#include "Animation/AnimInstance.h"

UAsyncLoadPersistentClass::UAsyncLoadPersistentClass(const FObjectInitializer& ObjectInitializer) 
	: Super(ObjectInitializer), AssetClass(nullptr), ObjectId(-1), JsonObject(FJsonObjectWrapper())
{
}

UAsyncLoadPersistentClass* UAsyncLoadPersistentClass::AsyncLoadPersistentClass(UObject* WorldContextObject, const TSoftClassPtr<UObject> AssetClass, const int32 ObjectId, const FJsonObjectWrapper& JsonObject)
{
	UAsyncLoadPersistentClass* BlueprintNode = NewObject<UAsyncLoadPersistentClass>();
	BlueprintNode->AssetClass = AssetClass;
	BlueprintNode->ObjectId = ObjectId;
	BlueprintNode->JsonObject = JsonObject;
	BlueprintNode->RegisterWithGameInstance(WorldContextObject);
	return BlueprintNode;
}

void UAsyncLoadPersistentClass::Activate()
{		
	if (UAssetManager* Manager = UAssetManager::GetIfInitialized())
	{
		// async load soft pointer
		const FStreamableDelegate Delegate1 = FStreamableDelegate::CreateUObject(this, &UAsyncLoadPersistentClass::OnClassAssetLoaded);
		FStreamableManager& Streamable = Manager->GetStreamableManager();
		Streamable.RequestAsyncLoad(AssetClass.ToSoftObjectPath(), Delegate1);
	}
	else {
		FFrame::KismetExecutionMessage(TEXT("AsyncLoadPersistentClass failed, because it couldn't get Asset Manager!"), ELogVerbosity::Error);
		SetReadyToDestroy();
	}		
}

void UAsyncLoadPersistentClass::OnClassAssetLoaded()
{
	if (UAssetManager* Manager = UAssetManager::GetIfInitialized())
	{
		FStreamableManager& Streamable = Manager->GetStreamableManager();
		if (Streamable.IsAsyncLoadComplete(AssetClass.ToSoftObjectPath()))
		{
			Completed.Broadcast(AssetClass.Get(), ObjectId, JsonObject);
		}
		else
		{
			FFrame::KismetExecutionMessage(TEXT("AsyncLoadPersistentClass failed to load the class!"), ELogVerbosity::Error);
		}
	}
	else {
		FFrame::KismetExecutionMessage(TEXT("AsyncLoadPersistentClass failed, because it couldn't get Asset Manager!"), ELogVerbosity::Error);
	}
	SetReadyToDestroy();
}