#pragma once

#include "CoreMinimal.h"
#include "WingServer.h"
#include "WingHandler.h"
#include "WingFetcher.h"
#include "WingUtils.h"
#include "WingMaterialParameter.h"
#include "Materials/MaterialInstanceConstant.h"
#include "MaterialTypes.h"
#include "MaterialInstance_ClearParameter.generated.h"


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

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

public:
	UPROPERTY(EditAnywhere, meta=(Description="Target material instance"))
	FString MaterialInstance;

	UPROPERTY(EditAnywhere, meta=(Description="Parameter name to clear"))
	FString Parameter;

	UPROPERTY(EditAnywhere, meta=(Description="Parameter association: 'Global', 'Layer', or 'Blend'. Default: 'Global'", Optional))
	FString ParameterAssociation = TEXT("Global");

	UPROPERTY(EditAnywhere, meta=(Description="Layer/blend index (0-based). Only used when ParameterAssociation is 'Layer' or 'Blend'", Optional))
	int32 ParameterLayer = INDEX_NONE;

	virtual void Register() override
	{
		UWingServer::AddHandler(this,
			TEXT("Remove a parameter override from a Material Instance, reverting it to the parent material's value."));
	}
	virtual void Handle() override
	{
		WingFetcher F;
		UMaterialInstanceConstant* MI = F.Asset(MaterialInstance).Cast<UMaterialInstanceConstant>();
		if (!MI) return;

		// Parse the association string.
		EMaterialParameterAssociation Association;
		if (!WingMaterialParameter::ParseMaterialParameterAssociation(ParameterAssociation, Association))
			return;

		FMaterialParameterInfo ParamID(*Parameter, Association, ParameterLayer);

		// Remove the override from all parameter arrays.
		auto RemoveFrom = [&](auto& Arr) {
			return Arr.RemoveAll([&](auto& Entry) { return Entry.ParameterInfo == ParamID; });
		};

		int32 Removed = 0;
		Removed += RemoveFrom(MI->ScalarParameterValues);
		Removed += RemoveFrom(MI->VectorParameterValues);
		Removed += RemoveFrom(MI->DoubleVectorParameterValues);
		Removed += RemoveFrom(MI->TextureParameterValues);
		Removed += RemoveFrom(MI->TextureCollectionParameterValues);
		Removed += RemoveFrom(MI->RuntimeVirtualTextureParameterValues);
		Removed += RemoveFrom(MI->SparseVolumeTextureParameterValues);
		Removed += RemoveFrom(MI->FontParameterValues);

		if (Removed == 0)
		{
			UWingServer::Printf(TEXT("No override found for parameter '%s' (association=%s layer=%d) on %s"),
				*Parameter, *ParameterAssociation, ParameterLayer, *WingUtils::FormatName(MI));
			return;
		}

		UWingServer::Printf(TEXT("Cleared override for '%s' on %s\n"),
			*Parameter, *WingUtils::FormatName(MI));
	}
};
