#include "PortaSubsystem.h"
#include "PortaUtils.h"
#include "PortaInterface.h"
#include "Modules/ModuleManager.h"

void UPortaGISubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	PortaUtils::GetEngineSubsystem<UPortaControlSubsystem>()->OnGameInstanceInit.Broadcast();
}

void UPortaGISubsystem::Deinitialize()
{
	PortaUtils::GetEngineSubsystem<UPortaControlSubsystem>()->OnGameInstanceDeinit.Broadcast();
}

void UPortaSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
	Init();

	auto Module = FModuleManager::GetModulePtr<FPortaInterfaceModule>("PortaInterface");
	auto Control = PortaUtils::GetEngineSubsystem<UPortaControlSubsystem>();
	Control->OnGameInstanceInit.AddUObject(this, &UPortaSubsystem::OnGameStart);
	if (Module->GameMode)
	{
		Control->OnGameInstanceDeinit.AddUObject(this, &UPortaSubsystem::OnGameStop);
	}
	else
	{
		Start();
	}
}

void UPortaSubsystem::Deinitialize()
{
	auto Module = FModuleManager::GetModuleChecked<FPortaInterfaceModule>("PortaInterface");
	if (!Module.GameMode)
	{
		Stop();
	}
	Deinit();
}

void UPortaSubsystem::OnGameStart()
{
	auto Module = FModuleManager::GetModuleChecked<FPortaInterfaceModule>("PortaInterface");
	if (Module.GameMode)
		Start();
	OnGameInstanceStart();
}

void UPortaSubsystem::OnGameStop()
{
	Stop();
}

UWorld* UPortaSubsystem::GetWorld() const
{
	return PortaUtils::GetCurrentWorld();
}
