#pragma once

#include "CoreMinimal.h"
#include "Factories/Factory.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFactories.h"
#include "WingPropHandle.h"
#include "Factories/BlueprintFunctionLibraryFactory.h"
#include "Create_UsingFactory.generated.h"

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Full asset path for the new asset (e.g. '/Game/MyFolder/MyAsset')"))
	FString Path;

	virtual void Register() override
	{
		TArray<UClass*> FactoryClasses;
		GetDerivedClasses(UFactory::StaticClass(), FactoryClasses);

		for (UClass* Class : FactoryClasses)
		{
			if (Class->HasAnyClassFlags(CLASS_Abstract)) continue;

			UFactory* CDO = Class->GetDefaultObject<UFactory>();
			if (!CDO->CanCreateNew() || !CDO->ShouldShowInNewMenu()) continue;

			WingPropHandle Props;
			TArray<TSharedPtr<IPropertyHandle>> ConfigProps = Props.AllProperties(CDO, true);
			if (ConfigProps.Num() > 0) continue;

			FString FactoryName = WingFactories::DeriveFactoryName(Class);
			FString CommandName = FString::Printf(TEXT("Create_%s"), *FactoryName);
			FString Doc = FString::Printf(TEXT("Create a new %s asset."), *FactoryName);
			UWingServer::AddHandler(this, CommandName, Class, EWingHandlerKind::Create, Doc);
		}

		UWingServer::AddHandler(this, TEXT("Create_BlueprintFunctionLibrary"),
			UBlueprintFunctionLibraryFactory::StaticClass(), EWingHandlerKind::Create,
			TEXT("Create a blueprint function library"));
	}

	virtual void Handle() override
	{
		UClass* FactoryClass = Cast<UClass>(ConfigurationObject);
		UFactory* Factory = NewObject<UFactory>(GetTransientPackage(), FactoryClass);
		WingFactories::CreateAsset(Path, Factory);
		UWingServer::Printf(TEXT("Created.\n"));
	}
};
