#pragma once

#include "CoreMinimal.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "WingServer.h"
#include "WingActorComponent.h"
#include "Engine/Blueprint.h"
#include "Engine/SimpleConstructionScript.h"
#include "Engine/SCS_Node.h"
#include "ActorComponent_Reparent.generated.h"


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

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Path to the component (e.g. '/Game/MyBP,component:MyComp')"))
	FString Component;

	UPROPERTY(EditAnywhere, meta=(Description="New parent component name."))
	FString Parent;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Change the parent of a component in a Blueprint's SimpleConstructionScript."));
	}
	virtual void Handle() override
	{
		WingFetcher F;
		UWingComponentReference* CompRef = F.Walk(Component).Cast<UWingComponentReference>();
		if (!CompRef) return;

		// Find the new parent among all components (if specified)
		UBlueprint *BP = CompRef->BP;
		TArray<UWingComponentReference*> AllComponents = UWingComponentReference::GetAll(BP);
		UWingComponentReference* NewParent = WingUtils::FindOneWithExternalID(Parent, AllComponents, TEXT("Component"));
		if (!NewParent) return;

		if (!CompRef->ReparentComponent(NewParent)) return;

		UWingServer::Printf(TEXT("Reparented component."));
	}
};
