// Fill out your copyright notice in the Description page of Project Settings.

#include "RecorderSession.h"
#include "Engine/World.h"
#include "Misc/Paths.h"
#include "HAL/PlatformFileManager.h"
#include "GenericPlatform/GenericPlatformFile.h"

bool URecorderSession::ShouldCreateSubsystem(UObject* Outer) const
{
	// One per game world (PIE world, packaged game). Don't spin up for editor preview / inactive worlds.
	if (UWorld* World = Cast<UWorld>(Outer))
	{
		return World->IsGameWorld();
	}
	return false;
}

void URecorderSession::Initialize(FSubsystemCollectionBase& Collection)
{
	Super::Initialize(Collection);
	SessionTimestamp = FDateTime::Now().ToString();
}

FString URecorderSession::GetOrCreateSessionDirectory(const FString& Root)
{
	if (!bDirectoryCreated)
	{
		FString Combined = FPaths::Combine(Root, TEXT("Session_") + SessionTimestamp);
		FPaths::NormalizeDirectoryName(Combined);

		IPlatformFile& PF = FPlatformFileManager::Get().GetPlatformFile();
		if (!PF.DirectoryExists(*Combined))
		{
			PF.CreateDirectoryTree(*Combined);
		}

		// Make sure it ends with a separator so callers can string-concat a filename.
		if (!Combined.EndsWith(TEXT("/")) && !Combined.EndsWith(TEXT("\\")))
		{
			Combined += TEXT("/");
		}

		CachedSessionDirectory = Combined;
		bDirectoryCreated = true;
	}
	return CachedSessionDirectory;
}
