#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "Engine/Blueprint.h"
#include "EdGraph/EdGraphNode.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "Blueprint_Compile.generated.h"


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

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Blueprint to compile"))
	FString Blueprint;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Compile a blueprint. "
			"Reports compiler warnings and errors."));
	}
	virtual void Handle() override
	{
		WingFetcher F(WingOut::Stdout);
		UBlueprint* BP = F.Asset(Blueprint).Cast<UBlueprint>();
		if (!BP) return;

		// Compile
		EBlueprintCompileOptions CompileOpts =
			EBlueprintCompileOptions::SkipSave |
			EBlueprintCompileOptions::SkipGarbageCollection |
			EBlueprintCompileOptions::SkipFiBSearchMetaUpdate;
		FKismetEditorUtilities::CompileBlueprint(BP, CompileOpts, nullptr);

		// Report compiler messages
		for (UEdGraphNode* Node : WingUtils::AllNodes(BP))
		{
			if (!Node->bHasCompilerMessage) continue;
			const TCHAR* Prefix = (Node->ErrorType == EMessageSeverity::Error) ? TEXT("ERROR") : TEXT("WARNING");
			WingOut::Stdout.Printf(TEXT("%s: [%s] %s: %s\n"),
				Prefix, *WingUtils::FormatName(Node->GetGraph()),
				*WingUtils::FormatName(Node), *Node->ErrorMsg);
		}

		WingOut::Stdout.Printf(TEXT("Compilation Done.\n"));
	}
};
