#include "ZMMOGameInstance.h"

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

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

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

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

	BindZeusDelegates(ZeusNet);

	if (!bAutoConnectOnStart)
	{
		return;
	}

	ZeusNet->ConnectToZeusServer(ZeusServerHost, ZeusServerPort);
}

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

	Super::Shutdown();
}

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

void UZMMOGameInstance::BindZeusDelegates(UZeusNetworkSubsystem* Zeus)
{
	if (!Zeus)
	{
		return;
	}
	Zeus->OnConnected.AddDynamic(this, &UZMMOGameInstance::HandleZeusConnected);
	Zeus->OnConnectionFailed.AddDynamic(this, &UZMMOGameInstance::HandleZeusConnectionFailed);
	Zeus->OnDisconnected.AddDynamic(this, &UZMMOGameInstance::HandleZeusDisconnected);
	Zeus->OnNetworkLog.AddDynamic(this, &UZMMOGameInstance::HandleZeusNetworkLog);
}

void UZMMOGameInstance::UnbindZeusDelegates(UZeusNetworkSubsystem* Zeus)
{
	if (!Zeus)
	{
		return;
	}
	Zeus->OnConnected.RemoveDynamic(this, &UZMMOGameInstance::HandleZeusConnected);
	Zeus->OnConnectionFailed.RemoveDynamic(this, &UZMMOGameInstance::HandleZeusConnectionFailed);
	Zeus->OnDisconnected.RemoveDynamic(this, &UZMMOGameInstance::HandleZeusDisconnected);
	Zeus->OnNetworkLog.RemoveDynamic(this, &UZMMOGameInstance::HandleZeusNetworkLog);
}

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

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

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

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