// Georgy Treshchev 2026 All Rights Reserved.

#include "RuntimeAudioImporterWebRTCAEC3.h"
#include "Interfaces/IPluginManager.h"

#define LOCTEXT_NAMESPACE "FRuntimeAudioImporterWebRTCAEC3Module"

void FRuntimeAudioImporterWebRTCAEC3Module::StartupModule()
{
#if PLATFORM_WINDOWS || PLATFORM_MAC || PLATFORM_LINUX
	const FString PluginDir = IPluginManager::Get().FindPlugin("RuntimeAudioImporterWebRTCAEC3")->GetBaseDir();
	const FString WebRTCAEC3SharedLibFilePath = FPaths::Combine(PluginDir, TEXT("Source"), TEXT("RuntimeAudioImporterWebRTCAEC3"), TEXT(PREPROCESSOR_TO_STRING(WEBRTCAEC3_SHAREDLIB_PATH)));
	const FString WebRTCAEC3SharedLibDirPath = FPaths::GetPath(WebRTCAEC3SharedLibFilePath);

	UE_LOG(LogRuntimeAudioImporterWebRTCAEC3, Log, TEXT("Loading WebRTC AEC3 dynamic/shared library from '%s'"), *WebRTCAEC3SharedLibFilePath);

	FPlatformProcess::PushDllDirectory(*FPaths::GetPath(WebRTCAEC3SharedLibDirPath));
	AEC3SharedLibHandle = FPlatformProcess::GetDllHandle(*WebRTCAEC3SharedLibFilePath);
	FPlatformProcess::PopDllDirectory(*FPaths::GetPath(WebRTCAEC3SharedLibDirPath));

	if (!AEC3SharedLibHandle)
	{
		UE_LOG(LogRuntimeAudioImporterWebRTCAEC3, Fatal, TEXT("Failed to load WebRTC AEC3"));
	}

	AEC3Feature = MakeShared<FWebRTCAEC3Feature>();
	IModularFeatures::Get().RegisterModularFeature(FRuntimeAECFeature::GetModularFeatureName(), AEC3Feature.Get());
	UE_LOG(LogTemp, Log, TEXT("RuntimeWebRTCAEC: Registered WebRTC AEC3 modular feature"));
#endif
}

void FRuntimeAudioImporterWebRTCAEC3Module::ShutdownModule()
{
	if (AEC3Feature.IsValid())
	{
		IModularFeatures::Get().UnregisterModularFeature(FRuntimeAECFeature::GetModularFeatureName(), AEC3Feature.Get());
		AEC3Feature.Reset();
	}
	UE_LOG(LogTemp, Log, TEXT("RuntimeWebRTCAEC: Unregistered WebRTC AEC3 modular feature"));
}

#undef LOCTEXT_NAMESPACE

IMPLEMENT_MODULE(FRuntimeAudioImporterWebRTCAEC3Module, RuntimeAudioImporterWebRTCAEC3)

DEFINE_LOG_CATEGORY(LogRuntimeAudioImporterWebRTCAEC3);