// Copyright (c) Microsoft Corporation. 
// Licensed under the MIT license.

#include "LODRecipeContentBrowserExtenders.h"
#include "LODRecipe.h"
#include "LODRecipeManager.h"

#include "AssetData.h"
#include "FrameWork/MultiBox/MultiBoxBuilder.h"
#include "Modules/ModuleManager.h"
#include "Telemetry.h"
#include "TelemetryManager.h"

#define LOCTEXT_NAMESPACE "LODRecipeContentBrowserExtenders"

FLODRecipeContentBrowserContextMenu::FLODRecipeContentBrowserContextMenu(const TArray<FAssetData>& InSelectedAssets)
	: SelectedAssets(InSelectedAssets)
{
	// Run through the assets to determine if any meet our criteria
	bool bAnyLODRecipe = false;
	for (auto AssetIt = SelectedAssets.CreateConstIterator(); AssetIt; ++AssetIt)
	{
		const FAssetData& Asset = *AssetIt;
		bAnyLODRecipe = bAnyLODRecipe || (Asset.AssetClass == ULODRecipe::StaticClass()->GetFName());
	}

	if (bAnyLODRecipe)
	{
		// Add the sprite actions sub-menu extender
		this->AddMenuExtension(
			"CommonAssetActions",
			EExtensionHook::Before,
			nullptr,
			FMenuExtensionDelegate::CreateStatic(&FLODRecipeContentBrowserContextMenu::CreateContextMenuGenerateLODs, SelectedAssets));
	}
}

void FLODRecipeContentBrowserContextMenu::CreateContextMenuGenerateLODs(FMenuBuilder& MenuBuilder, TArray<FAssetData> SelectedAssets)
{
	FUIAction GenerateLODsAction(
		FExecuteAction::CreateStatic(&FLODRecipeContentBrowserContextMenu::GenerateLODsClicked, SelectedAssets));

	MenuBuilder.BeginSection("LODRecipe", LOCTEXT("LODRecipeHeading", "LOD Recipe"));
	{
		MenuBuilder.AddMenuEntry(
			LOCTEXT("LODRecipeCBContextMenu_GenerateLODs", "Generate LODs"),
			LOCTEXT("LODRecipeCBContextMenu_GenerateLODsToolTip", "Generate all LODs"),
			FSlateIcon(/*FEditorStyle::GetStyleSetName(), "SimplygonIcon.TabIcon"*/),
			GenerateLODsAction,
			NAME_None,
			EUserInterfaceActionType::Button);
	}
	MenuBuilder.EndSection();
}

void FLODRecipeContentBrowserContextMenu::GenerateLODsClicked(TArray<FAssetData> SelectedAssets)
{
	
	TArray<ULODRecipe*> SelectedRecipes;
	for (const FAssetData& AssetData : SelectedAssets)
	{
		ULODRecipe* LODRecipe = Cast<ULODRecipe>(AssetData.GetAsset());
		if (LODRecipe)
		{
			SelectedRecipes.Add(LODRecipe);
		}
	}

	FTelemetryBuilder Builder;
	Builder.SetProperties({ FTelemetry::Prop(TEXT("action"), TEXT("build_selected")),
		FTelemetry::Prop(TEXT("num_recipes"), SelectedRecipes.Num()),
		});
	
	FTelemetry::Record(SGTC::ContextMenu, SGTC::LODRecipe, MoveTemp(Builder));


	FLODRecipeManager::Get().Build(SelectedRecipes);
}

#undef LOCTEXT_NAMESPACE
