#include "ZeusGameInstance.h"

#include "ZMMO.h"
#include "ZeusNetworkSubsystem.h"

void UZeusGameInstance::Init()
{
	Super::Init();

	UE_LOG(LogZMMO, Log, TEXT("ZeusGameInstance::Init AutoConnect=%s Host=%s Port=%d"),
		bAutoConnectOnStart ? TEXT("true") : TEXT("false"),
		*ZeusServerHost,
		ZeusServerPort);

	UZeusNetworkSubsystem* ZeusNet = GetZeusNetwork();
	if (!ZeusNet)
	{
		UE_LOG(LogZMMO, Warning, TEXT("ZeusGameInstance: ZeusNetworkSubsystem unavailable; ZeusNetwork plugin enabled?"));
		return;
	}

	BindZeusDelegates(ZeusNet);

	if (!bAutoConnectOnStart)
	{
		return;
	}

	ZeusNet->ConnectToZeusServer(ZeusServerHost, ZeusServerPort);
}

void UZeusGameInstance::Shutdown()
{
	if (UZeusNetworkSubsystem* ZeusNet = GetZeusNetwork())
	{
		UnbindZeusDelegates(ZeusNet);
		if (ZeusNet->IsConnected())
		{
			ZeusNet->DisconnectFromZeusServer();
		}
	}

	Super::Shutdown();
}

UZeusNetworkSubsystem* UZeusGameInstance::GetZeusNetwork() const
{
	return GetSubsystem<UZeusNetworkSubsystem>();
}

void UZeusGameInstance::BindZeusDelegates(UZeusNetworkSubsystem* Zeus)
{
	if (!Zeus)
	{
		return;
	}
	Zeus->OnConnected.AddDynamic(this, &UZeusGameInstance::HandleZeusConnected);
	Zeus->OnConnectionFailed.AddDynamic(this, &UZeusGameInstance::HandleZeusConnectionFailed);
	Zeus->OnDisconnected.AddDynamic(this, &UZeusGameInstance::HandleZeusDisconnected);
	// OnNetworkLog: NAO assinamos. Plugin ja loga em LogZeusNetwork (console)
	// + arquivo proprio em Saved/Logs/ZeusNetwork/. Forwarding em LogZMMO era
	// diagnostico inicial (sessao 2026-05-07); agora gera duplicacao de cada
	// linha. Remova esta nota e descomente abaixo se quiser ver no LogZMMO:
	// Zeus->OnNetworkLog.AddDynamic(this, &UZeusGameInstance::HandleZeusNetworkLog);
}

void UZeusGameInstance::UnbindZeusDelegates(UZeusNetworkSubsystem* Zeus)
{
	if (!Zeus)
	{
		return;
	}
	Zeus->OnConnected.RemoveDynamic(this, &UZeusGameInstance::HandleZeusConnected);
	Zeus->OnConnectionFailed.RemoveDynamic(this, &UZeusGameInstance::HandleZeusConnectionFailed);
	Zeus->OnDisconnected.RemoveDynamic(this, &UZeusGameInstance::HandleZeusDisconnected);
	// OnNetworkLog: nao foi assinado (ver BindZeusDelegates) — nada a remover.
}

void UZeusGameInstance::HandleZeusConnected()
{
	UE_LOG(LogZMMO, Log, TEXT("[Zeus] Connected to server %s:%d"), *ZeusServerHost, ZeusServerPort);
}

void UZeusGameInstance::HandleZeusConnectionFailed(FString Reason)
{
	UE_LOG(LogZMMO, Warning, TEXT("[Zeus] Connection failed: %s"), *Reason);
}

void UZeusGameInstance::HandleZeusDisconnected()
{
	UE_LOG(LogZMMO, Log, TEXT("[Zeus] Disconnected."));
}

void UZeusGameInstance::HandleZeusNetworkLog(FString Message)
{
	UE_LOG(LogZMMO, Log, TEXT("[Zeus] %s"), *Message);
}
