#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingBasics.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "Materials/Material.h"
#include "Materials/MaterialInterface.h"
#include "Materials/MaterialInstanceConstant.h"
#include "Factories/MaterialInstanceConstantFactoryNew.h"
#include "WingFactories.h"
#include "Create_MaterialInstance.generated.h"


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

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

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

	UPROPERTY(EditAnywhere, meta=(Description="Parent material package path (Material or Material Instance)"))
	FString ParentMaterial;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Create a new Material Instance Constant asset with a specified parent material."));
	}

	virtual void Handle() override
	{
		// Verify that the asset path is valid and available.
		if (!WingFactories::CheckNewAssetPath(Path, WingOut::Stdout)) return;
		
		// Load parent material by package path.
		WingFetcher F(WingOut::Stdout);
		UMaterialInterface* ParentObj = F.Asset(ParentMaterial).Cast<UMaterialInterface>();
		if (!ParentObj) return;

		// Create a factory, then use it to create an asset.
		UMaterialInstanceConstantFactoryNew* Factory =
			NewObject<UMaterialInstanceConstantFactoryNew>();
		if (!WingUtils::CheckNewObjectNotNull(
			Factory, TEXT("factory"), WingOut::Stdout)) return;
		UObject* MIO = WingFactories::CreateAsset(Path,
			Factory, UMaterialInstanceConstant::StaticClass(), WingOut::Stdout);
		if (!MIO) return;

		// Set parent.
		UMaterialInstanceConstant* MI = Cast<UMaterialInstanceConstant>(MIO);
		MI->Parent = ParentObj;

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