#include "WingMaterialParameter.h"
#include "WingUtils.h"
#include "WingServer.h"

TMap<FMaterialParameterInfo, FMaterialParameterMetadata> WingMaterialParameter::GetMaterialParameters(UMaterialInterface* Material)
{
	TMap<FMaterialParameterInfo, FMaterialParameterMetadata> Result;
	if (!Material) return Result;
	TMap<FMaterialParameterInfo, FMaterialParameterMetadata> Temp;
	for (int32 i = 0; i < (int32)EMaterialParameterType::NumRuntime; i++)
	{
		Material->GetAllParametersOfType((EMaterialParameterType)i, Temp);
		Result.Append(Temp);
	}
	return Result;
}

bool WingMaterialParameter::ParseMaterialParameterAssociation(const FString& Str, EMaterialParameterAssociation& OutAssociation)
{
	if (Str.Equals(TEXT("Global"), ESearchCase::IgnoreCase))
		OutAssociation = GlobalParameter;
	else if (Str.Equals(TEXT("Layer"), ESearchCase::IgnoreCase))
		OutAssociation = LayerParameter;
	else if (Str.Equals(TEXT("Blend"), ESearchCase::IgnoreCase))
		OutAssociation = BlendParameter;
	else
	{
		UWingServer::Printf(TEXT("ERROR: Invalid ParameterAssociation '%s' (expected 'Global', 'Layer', or 'Blend')\n"), *Str);
		return false;
	}
	return true;
}

void WingMaterialParameter::FormatMaterialParameter(const FMaterialParameterInfo& Info, const FMaterialParameterMetadata& Meta)
{
	// Association prefix for layer/blend parameters.
	FString Prefix;
	if (Info.Association == LayerParameter)
		Prefix = FString::Printf(TEXT("[Layer %d] "), Info.Index);
	else if (Info.Association == BlendParameter)
		Prefix = FString::Printf(TEXT("[Blend %d] "), Info.Index);

	switch (Meta.Value.Type)
	{
	case EMaterialParameterType::Scalar:
		UWingServer::Printf(TEXT("  %sScalar \"%s\" = %g\n"), *Prefix, *Info.Name.ToString(), Meta.Value.AsScalar());
		break;
	case EMaterialParameterType::Vector:
	{
		FLinearColor C = Meta.Value.AsLinearColor();
		UWingServer::Printf(TEXT("  %sVector \"%s\" = (R=%.3f, G=%.3f, B=%.3f, A=%.3f)\n"),
			*Prefix, *Info.Name.ToString(), C.R, C.G, C.B, C.A);
		break;
	}
	case EMaterialParameterType::DoubleVector:
	{
		FVector4d V = Meta.Value.AsVector4d();
		UWingServer::Printf(TEXT("  %sDoubleVector \"%s\" = (%.3f, %.3f, %.3f, %.3f)\n"),
			*Prefix, *Info.Name.ToString(), V.X, V.Y, V.Z, V.W);
		break;
	}
	case EMaterialParameterType::Texture:
	{
		UTexture* Tex = Cast<UTexture>(Meta.Value.AsTextureObject());
		UWingServer::Printf(TEXT("  %sTexture \"%s\" = %s\n"),
			*Prefix, *Info.Name.ToString(), Tex ? *WingUtils::FormatName(Tex) : TEXT("None"));
		break;
	}
	case EMaterialParameterType::StaticSwitch:
		UWingServer::Printf(TEXT("  %sStaticSwitch \"%s\" = %s\n"),
			*Prefix, *Info.Name.ToString(), Meta.Value.AsStaticSwitch() ? TEXT("true") : TEXT("false"));
		break;
	default:
		UWingServer::Printf(TEXT("  %sType%d \"%s\"\n"), *Prefix, (int)Meta.Value.Type, *Info.Name.ToString());
		break;
	}
}

