#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "Materials/Material.h"
#include "Material_Compile.generated.h"


// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

UCLASS()
class UWing_Material_Compile : public UWingHandler
{
	GENERATED_BODY()

public:
	UPROPERTY(EditAnywhere, meta=(Description="Material name or package path"))
	FString Material;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Force recompile a material and check for compilation errors."));
	}
	virtual void Handle() override
	{
		// Load material
		WingFetcher F(WingOut::Stdout);
		UMaterial* MaterialObj = F.Asset(Material).Cast<UMaterial>();
		if (!MaterialObj) return;

		// Force recompile
		MaterialObj->ForceRecompileForRendering();

		// Wait for compilation to finish, then check for errors
		FMaterialResource* Resource = MaterialObj->GetMaterialResource(GMaxRHIFeatureLevel);
		TArray<FString> Errors;
		if (Resource)
		{
			Resource->FinishCompilation();
			Errors = Resource->GetCompileErrors();
		}

		if (Errors.IsEmpty())
		{
			WingOut::Stdout.Printf(TEXT("%s compiled successfully.\n"), *WingUtils::FormatName(MaterialObj));
		}
		else
		{
			WingOut::Stdout.Printf(TEXT("%s compiled with %d error(s):\n"), *WingUtils::FormatName(MaterialObj), Errors.Num());
			for (const FString& Err : Errors)
			{
				WingOut::Stdout.Printf(TEXT("  %s\n"), *Err);
			}
		}
	}
};
