#pragma once

#include "CoreMinimal.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "WingServer.h"
#include "WingComponent.h"
#include "Engine/Blueprint.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 ComponentPath;

	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(WingOut::Stdout);
		UWingComponentRef* CompRef = F.Walk(ComponentPath).Cast<UWingComponentRef>();
		if (!CompRef) return;

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

		if (!UWingComponent::ReparentComponent(CompRef, NewParent.Get(), WingOut::Stdout)) return;

		WingOut::Stdout.Printf(TEXT("Reparented component."));
	}
};
