#include "Easy2SfxImporterEditor.h"

#include "AssetImportTask.h"
#include "AssetToolsModule.h"
#include "ContentBrowserModule.h"
#include "IContentBrowserSingleton.h"
#include "DesktopPlatformModule.h"
#include "IDesktopPlatform.h"
#include "IAssetTools.h"
#include "Framework/Application/SlateApplication.h"
#include "Misc/MessageDialog.h"
#include "Misc/Paths.h"
#include "HAL/PlatformFileManager.h"
#include "ToolMenus.h"
#include "Modules/ModuleManager.h"

#define LOCTEXT_NAMESPACE "Easy2SfxImporterEditor"

namespace Easy2SfxImporterEditorPrivate
{
	static bool IsAudioFile(const FString& FilePath)
	{
		const FString Ext = FPaths::GetExtension(FilePath).ToLower();
		return Ext == TEXT("wav") || Ext == TEXT("wave")
			|| Ext == TEXT("mp3") || Ext == TEXT("ogg") || Ext == TEXT("flac")
			|| Ext == TEXT("aif") || Ext == TEXT("aiff") || Ext == TEXT("m4a")
			|| Ext == TEXT("wma");
	}

	static void CollectAudioFiles(const FString& RootFolder, TArray<FString>& OutFiles)
	{
		TArray<FString> AllFiles;
		IFileManager::Get().FindFilesRecursive(AllFiles, *RootFolder, TEXT("*"), true, false);
		for (const FString& Path : AllFiles)
		{
			if (IsAudioFile(Path))
			{
				OutFiles.Add(Path);
			}
		}
		OutFiles.Sort();
	}
}

void FEasy2SfxImporterEditorModule::StartupModule()
{
	UToolMenus::RegisterStartupCallback(FSimpleMulticastDelegate::FDelegate::CreateLambda([]()
	{
		FToolMenuOwnerScoped OwnerScoped(UE_MODULE_NAME);
		UToolMenu* Menu = UToolMenus::Get()->ExtendMenu("LevelEditor.MainMenu.Tools");
		FToolMenuSection& Section = Menu->FindOrAddSection("Easy2SfxImporter", LOCTEXT("Easy2SfxHeading", "Easy2Sfx"));
		Section.AddMenuEntry(
			"Easy2SfxImportSession",
			LOCTEXT("ImportSessionLabel", "Import Easy2Sfx session folder..."),
			LOCTEXT("ImportSessionTooltip", "Pick the session folder from disk. Audio imports to Content/Easy2Sfx/<session folder name>/ with original file names."),
			FSlateIcon(),
			FUIAction(FExecuteAction::CreateStatic(&FEasy2SfxImporterEditorModule::ImportSessionFolder))
		);
	}));
}

void FEasy2SfxImporterEditorModule::ShutdownModule()
{
}

void FEasy2SfxImporterEditorModule::ImportSessionFolder()
{
	IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get();
	if (!DesktopPlatform)
	{
		FMessageDialog::Open(EAppMsgType::Ok, LOCTEXT("NoDesktop", "Desktop platform not available."));
		return;
	}

	const void* ParentWindow = FSlateApplication::Get().FindBestParentWindowHandleForDialogs(nullptr);
	FString FolderPath;
	const FString Title = LOCTEXT("PickSessionFolder", "Select Easy2Sfx session folder (folder name becomes the subfolder under Easy2Sfx)").ToString();
	const bool bPicked = DesktopPlatform->OpenDirectoryDialog(
		ParentWindow,
		Title,
		FPaths::ProjectDir(),
		FolderPath
	);

	if (!bPicked || FolderPath.IsEmpty())
	{
		return;
	}

	FPaths::NormalizeDirectoryName(FolderPath);

	FString SessionName = FPaths::GetCleanFilename(FolderPath);
	for (TCHAR& C : SessionName)
	{
		if (C == TEXT('\\') || C == TEXT('/') || C == TEXT(':') || C == TEXT('*') || C == TEXT('?')
			|| C == TEXT('"') || C == TEXT('<') || C == TEXT('>') || C == TEXT('|'))
		{
			C = TEXT('_');
		}
	}
	if (SessionName.IsEmpty())
	{
		SessionName = TEXT("Session");
	}

	TArray<FString> AudioFiles;
	Easy2SfxImporterEditorPrivate::CollectAudioFiles(FolderPath, AudioFiles);

	if (AudioFiles.Num() == 0)
	{
		FMessageDialog::Open(EAppMsgType::Ok, FText::Format(
			LOCTEXT("NoAudio", "No supported audio files found under:\n{0}\n\nSupported: wav, mp3, ogg, flac, aif, m4a, wma."),
			FText::FromString(FolderPath)));
		return;
	}

	const FString DestPath = FString::Printf(TEXT("/Game/Easy2Sfx/%s"), *SessionName);

	FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
	IAssetTools& AssetTools = AssetToolsModule.Get();

	TArray<UAssetImportTask*> Tasks;
	Tasks.Reserve(AudioFiles.Num());

	for (const FString& FilePath : AudioFiles)
	{
		UAssetImportTask* Task = NewObject<UAssetImportTask>();
		Task->AddToRoot();
		Task->Filename = FilePath;
		Task->DestinationPath = DestPath;
		Task->bAutomated = true;
		Task->bSave = true;
		Task->bReplaceExisting = true;
		Tasks.Add(Task);
	}

	AssetTools.ImportAssetTasks(Tasks);

	for (UAssetImportTask* Task : Tasks)
	{
		Task->RemoveFromRoot();
	}

	FContentBrowserModule& ContentBrowserModule = FModuleManager::LoadModuleChecked<FContentBrowserModule>("ContentBrowser");
	TArray<FString> FoldersToSync;
	FoldersToSync.Add(DestPath);
	ContentBrowserModule.Get().SyncBrowserToFolders(FoldersToSync);

	FMessageDialog::Open(EAppMsgType::Ok, FText::Format(
		LOCTEXT("Done", "Imported {0} sound file(s) into:\n{1}"),
		FText::AsNumber(AudioFiles.Num()),
		FText::FromString(DestPath)));
}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FEasy2SfxImporterEditorModule, Easy2SfxImporterEditor)
