// Copyright Epic Games, Inc. All Rights Reserved.

#include "AIGC.h"

#include "AIGCStyle.h"
#include "AssetToolsModule.h"
#include "FileHelpers.h"
#include "LevelEditor.h"
#include "ToolMenu.h"
#include "ToolMenus.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Misc/MessageDialog.h"
#include "UObject/SavePackage.h"
#include "Widget/AIGCWindow.h"

#define LOCTEXT_NAMESPACE "FAIGCModule"
#define AIGCWindowName FName("AIGC")



void FAIGCModule::StartupModule()
{
	// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module

	//添加style
	FAIGCStyle::Initialize();
	FAIGCStyle::ReloadTextures();
	// //注册Command
	// FAIGCCommands::Register();
	// PluginCommands = MakeShareable(new FUICommandList);
	// //绑定动作
	// PluginCommands->MapAction(
	// FAIGCCommands::Get().MenuAction,
	// FExecuteAction::CreateRaw(this, &FAIGCModule::MenuClicked),
	// FCanExecuteAction());
	//
	// PluginCommands->MapAction(
	// FAIGCCommands::Get().SubMenuAction,
	// FExecuteAction::CreateRaw(this, &FAIGCModule::SubMenuClicked),
	// FCanExecuteAction());
	//添加菜单
	UToolMenu* menu = UToolMenus::Get()->FindMenu(FName("LevelEditor.MainMenu.AIGC"));
	if (!menu)
	{
		menu = UToolMenus::Get()->ExtendMenu("LevelEditor.MainMenu");
		FToolMenuSection& section = menu->FindOrAddSection(FName("TestSection"));
		// 添加子菜单入口
		section = menu->FindOrAddSection(FName("AIGC Section"));
		FToolMenuEntry& entry = section.AddSubMenu("AIGC Section", FText::FromString("AIGC"),
		                                           FText::FromString("AIGC ToolTip"),
		                                           FNewToolMenuDelegate::CreateLambda([this](UToolMenu* SubMenu)
		                                           {
			                                           // 填充第一个子菜单项
			                                           FToolMenuSection& SubSection = SubMenu->AddSection("AIChat");
			                                           SubSection.AddMenuEntry(
				                                           "AIChat",
				                                           LOCTEXT("AIChat", "生成NPC对话"),
				                                           LOCTEXT("AIChatToolTip", ""),
				                                           FSlateIcon(FAIGCStyle::GetStyleSetName(), "AIGCStyle.AIChat"),
				                                           FUIAction(FExecuteAction::CreateLambda([this]()
				                                           {
				                                           		FGlobalTabmanager::Get()->TryInvokeTab(AIGCWindowName);
				                                           })));

			                                           // // 填充第二个子菜单项
			                                           // FToolMenuSection& SubSection2 = SubMenu->AddSection(
				                                          //  "SubSection2");
			                                           // SubSection.AddMenuEntry(
				                                          //  "Submenu2",
				                                          //  LOCTEXT("Action1Label", "生成模型2"),
				                                          //  LOCTEXT("Action1Tooltip", "触发模型生成2"),
				                                          //  FSlateIcon(FAIGCStyle::GetStyleSetName(), "AIGCStyle.AIChat"),
				                                          //  FToolUIActionChoice(
					                                         //   FAIGCCommands::Get().SubMenuAction, *PluginCommands));
		                                           }),
		                                           false, // 是否动态生成
		                                           FSlateIcon());
		entry.InsertPosition = FToolMenuInsert("Help", EToolMenuInsertType::After); //将自定义的菜单项置于"Help"菜单项的后面

		menu = UToolMenus::Get()->RegisterMenu(FName("LevelEditor.MainMenu.AIGC"));
		
	}

	//注册窗口
	FGlobalTabmanager::Get()->RegisterNomadTabSpawner(AIGCWindowName, FOnSpawnTab::CreateRaw(this, &FAIGCModule::OnSpawnPluginTab))
		.SetDisplayName(LOCTEXT("AIGCWindow", "AIGCWindow"))
		.SetMenuType(ETabSpawnerMenuType::Hidden);
}


// void FAIGCModule::SubMenuClicked()
// {
// 	UE_LOG(LogTemp, Warning, TEXT("Generate Model"));
// 	FMessageDialog::Open(EAppMsgType::Ok, FText::FromString("4444555"));
// }




void FAIGCModule::ShutdownModule()
{
	// This function may be called during shutdown to clean up your module.  For modules that support dynamic reloading,
	// we call this function before unloading the module.
	UToolMenus::UnregisterOwner(this);
	FAIGCStyle::Shutdown();
	//FAIGCCommands::Unregister();
	FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(AIGCWindowName);
}



TSharedRef<SDockTab> FAIGCModule::OnSpawnPluginTab(const FSpawnTabArgs& SpawnTabArgs)
{
	FText WidgetText = FText::Format(
    		LOCTEXT("WindowWidgetText", "Add code to {0} in {1} to override this window's contents"),
    		FText::FromString(TEXT("FTestModule::OnSpawnPluginTab")),
    		FText::FromString(TEXT("Test.cpp"))
    		);
    
    	return SNew(SDockTab)
    		.TabRole(ETabRole::NomadTab)
    		[
    			// Put your tab content here!
    			SNew(SBox)
    			.HAlign(HAlign_Center)
    			.VAlign(VAlign_Center)
    			[
    				SNew(SAIGCWindow)
    			]
    		];
}

void FAIGCModule::CreateOrAddData(const FString& DataTablePath, const FString& RowValue)
{
	FString PackagePath, AssetName;
	DataTablePath.Split(".", &PackagePath, &AssetName);
	// 1. 检测资源是否存在
	UDataTable* DataTable = LoadObject<UDataTable>(nullptr, *DataTablePath);
	if (!DataTable) {
		// 2. 创建新DataTable
		UPackage* Package = CreatePackage(*PackagePath);
		DataTable = NewObject<UDataTable>(Package, FName(*AssetName), RF_Public | RF_Standalone );
		DataTable->RowStruct = FNPCChatRow::StaticStruct();
	}

	// 3. 添加数据
	FNPCChatRow NewRow;
	NewRow.ChatText = RowValue;
	FString DynamicName = FString::Printf(TEXT("DynamicRow%d"), DataTable->GetRowMap().Num());
	DataTable->AddRow(FName(*DynamicName), NewRow);
	// 保存
	DataTable->MarkPackageDirty();
	// 保存参数配置
	FSavePackageArgs SaveArgs;
	SaveArgs.TopLevelFlags = RF_Standalone | RF_Public;
	SaveArgs.SaveFlags = SAVE_NoError; 
	FString FilePath = FPackageName::LongPackageNameToFilename(PackagePath) + ".uasset";
	UPackage::SavePackage(DataTable->GetPackage(), DataTable, *FilePath, SaveArgs);
}

#undef LOCTEXT_NAMESPACE
	
IMPLEMENT_MODULE(FAIGCModule, AIGC)