// Copyright (c) Microsoft Corporation. 
// Licensed under the MIT license.

#include "SimplygonTestsHelper.h"

#include "HierarchicalLODUtilitiesModule.h"
#include "HierarchicalLODProxyProcessor.h"
#include "HAL/ThreadManager.h"

#include "LODRecipe.h"

DEFINE_LOG_CATEGORY_STATIC(LogSimplygonTestsHelper, All, All);

template<typename T>
T* SimplygonTestsHelper::GetAsset(ESimplygonTestAsset Asset)
{
	const FString AssetPath = AssetToPath[Asset];
	T* Mesh = SimplygonTestsHelper::GetAssetByPath<T>(FName(AssetPath));
	if (!Mesh)
	{
		UE_LOG(LogSimplygonTestsHelper, Error, TEXT("Failed to find Mesh: %s"), *AssetPath);
		return nullptr;
	}

	return Mesh;
}

bool SimplygonTestsHelper::WaitForHLODProcessor(const double Timeout)
{
    FHierarchicalLODUtilitiesModule& Module = FModuleManager::LoadModuleChecked<FHierarchicalLODUtilitiesModule>("HierarchicalLODUtilities");
    FHierarchicalLODProxyProcessor* Processor = Module.GetProxyProcessor();

    double StartTime = FPlatformTime::Seconds();
    double Duration = 0.0;

    while (Processor->IsProxyGenerationRunning())
    {
        Duration = FPlatformTime::Seconds() - StartTime;
        if ( Duration >= Timeout)
			return false;

        FTicker::GetCoreTicker().Tick(FApp::GetDeltaTime());
        FThreadManager::Get().Tick();
        FTaskGraphInterface::Get().ProcessThreadUntilIdle(ENamedThreads::GameThread);
        FPlatformProcess::Sleep(0.1f);
    }

	return true;
}

ULODRecipe* SimplygonTestsHelper::CreateLODRecipe()
{
	ULODRecipe* LODRecipe = NewObject<ULODRecipe>(GetTransientPackage(), NAME_None, RF_Transient);
	// Add to root to make sure GC doesn't remove it
	LODRecipe->AddToRoot();
	return LODRecipe;
}