// Copyright Pacificao. All Rights Reserved.

#if WITH_EDITOR && WITH_DEV_AUTOMATION_TESTS

#include "AgrarianEditorAutomationLibrary.h"
#include "HAL/PlatformTime.h"
#include "Misc/AutomationTest.h"
#include "Tests/AutomationEditorCommon.h"

namespace
{
constexpr const TCHAR* ShelterClassPath = TEXT("/Game/Agrarian/Blueprints/Structures/BP_PrimitiveShelter.BP_PrimitiveShelter_C");
constexpr const TCHAR* PersistenceTestSlot = TEXT("AgrarianAutomationPersistence");

class FAgrarianCreateBlankMapCommand final : public IAutomationLatentCommand
{
public:
	explicit FAgrarianCreateBlankMapCommand(FAutomationTestBase* InTest)
		: Test(InTest)
	{
	}

	virtual bool Update() override
	{
		UWorld* EditorWorld = FAutomationEditorCommonUtils::CreateNewMap();
		if (!EditorWorld && Test)
		{
			Test->AddError(TEXT("Could not create blank editor map for persistence subsystem test"));
		}

		return true;
	}

private:
	FAutomationTestBase* Test = nullptr;
};

class FAgrarianWaitSecondsCommand final : public IAutomationLatentCommand
{
public:
	explicit FAgrarianWaitSecondsCommand(const double InWaitSeconds)
		: EndTime(FPlatformTime::Seconds() + InWaitSeconds)
	{
	}

	virtual bool Update() override
	{
		return FPlatformTime::Seconds() >= EndTime;
	}

private:
	double EndTime = 0.0;
};

class FAgrarianRunPersistenceSubsystemCommand final : public IAutomationLatentCommand
{
public:
	explicit FAgrarianRunPersistenceSubsystemCommand(FAutomationTestBase* InTest)
		: Test(InTest)
	{
	}

	virtual bool Update() override
	{
		if (!Test)
		{
			return true;
		}

		UClass* ShelterClass = StaticLoadClass(AActor::StaticClass(), nullptr, ShelterClassPath);
		if (!ShelterClass)
		{
			Test->AddError(FString::Printf(TEXT("Could not load shelter class: %s"), ShelterClassPath));
			return true;
		}

		const FString Result = UAgrarianEditorAutomationLibrary::RunPersistenceSubsystemSmokeTest(ShelterClass, PersistenceTestSlot);
		if (!Result.StartsWith(TEXT("PASS:")))
		{
			Test->AddError(Result);
			return true;
		}

		Test->AddInfo(Result);
		return true;
	}

private:
	FAutomationTestBase* Test = nullptr;
};
}

IMPLEMENT_SIMPLE_AUTOMATION_TEST(
	FAgrarianPersistenceSubsystemAutomationTest,
	"Agrarian.PersistenceSubsystem.LiveGameInstance",
	EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter)

bool FAgrarianPersistenceSubsystemAutomationTest::RunTest(const FString& Parameters)
{
	ADD_LATENT_AUTOMATION_COMMAND(FAgrarianCreateBlankMapCommand(this));
	ADD_LATENT_AUTOMATION_COMMAND(FStartPIECommand(true));
	ADD_LATENT_AUTOMATION_COMMAND(FAgrarianWaitSecondsCommand(1.0));
	ADD_LATENT_AUTOMATION_COMMAND(FAgrarianRunPersistenceSubsystemCommand(this));
	ADD_LATENT_AUTOMATION_COMMAND(FEndPlayMapCommand());

	return true;
}

#endif
