// Fill out your copyright notice in the Description page of Project Settings.


#include "CraftingRecipeDataAsset.h"

#include "ItemDataAsset.h"

#if WITH_EDITOR
#include "Misc/DataValidation.h"
#endif

#define LOCTEXT_NAMESPACE "Crafting"

FText UCraftingRecipeDataAsset::GetDisplayName() const
{
	if (!DisplayNameOverride.IsEmpty())
	{
		return DisplayNameOverride;
	}

	return ResultItem ? ResultItem->DisplayName : FText::GetEmpty();
}

UTexture2D* UCraftingRecipeDataAsset::GetIcon() const
{
	if (IconOverride)
	{
		return IconOverride;
	}

	return ResultItem ? ResultItem->Icon : nullptr;
}

#if WITH_EDITOR
EDataValidationResult UCraftingRecipeDataAsset::IsDataValid(FDataValidationContext& Context) const
{
	EDataValidationResult Result = Super::IsDataValid(Context);

	if (!ResultItem)
	{
		Context.AddError(LOCTEXT("RecipeNoResult", "This recipe has no result item: it would consume the ingredients and give nothing back."));
		Result = EDataValidationResult::Invalid;
	}

	if (RecipeId.IsNone())
	{
		Context.AddWarning(LOCTEXT("RecipeNoId", "RecipeId is empty. Saved recipe unlocks will not be able to identify this recipe."));
	}

	// Deux lignes portant le meme objet donneraient un cout affiche en double
	// dans le panneau de detail, alors que la verification, elle, les cumule.
	// L'ecart entre les deux est indetectable a la lecture de l'asset.
	TSet<const UItemDataAsset*> SeenItems;
	SeenItems.Reserve(Ingredients.Num());

	for (int32 Index = 0; Index < Ingredients.Num(); ++Index)
	{
		const FCraftIngredient& Ingredient = Ingredients[Index];

		if (!Ingredient.Item)
		{
			Context.AddError(FText::Format(
				LOCTEXT("RecipeNullIngredient", "Ingredient {0} has no item assigned."), Index));
			Result = EDataValidationResult::Invalid;
			continue;
		}

		bool bAlreadySeen = false;
		SeenItems.Add(Ingredient.Item, &bAlreadySeen);
		if (bAlreadySeen)
		{
			Context.AddError(FText::Format(
				LOCTEXT("RecipeDuplicateIngredient", "Item {0} appears twice in the ingredients. Merge them into a single line."),
				FText::FromString(Ingredient.Item->GetName())));
			Result = EDataValidationResult::Invalid;
		}
	}

	return Result;
}
#endif

#undef LOCTEXT_NAMESPACE
