// (CVN) - Candy Valley Network GmbH

#include "LovenseToy.h"

// EXTERNAL INCLUDES

// INTERNAL INCLUDES
#include "LovenseManager.h"
#include "Adapters/ILovenseAdapter.h"


ULovenseToy::ULovenseToy() {
	this->toyDescription = FLovenseToyDescription();
	this->commandDelayTimers = { };
}

FString ULovenseToy::GetFullToyName() {
	if (!this->IsValidToy()) return NSLOCTEXT("ULovenseToy", "InvalidLovenseToy", "Invalid Toy").ToString();

	FString output = this->toyDescription.name;

	if (!this->toyDescription.version.IsEmpty()) {
		output.Append(TEXT(" "));
		output.Append(this->toyDescription.version);
	}

	if (!this->toyDescription.nickname.IsEmpty()) {
		output.Append(TEXT(" ("));
		output.Append(this->toyDescription.nickname);
		output.Append(TEXT(")"));
	}

	return output;
}

FString ULovenseToy::GetAssociatedAdapterPlatformName() {
	return this->IsValidToy()
		? this->lovenseAdapter->GetAdapterDescription().appType + TEXT(" ") + this->lovenseAdapter->GetAdapterDescription().platform
		: NSLOCTEXT("ULovenseToy", "UnknownPlatformName", "Unknown").ToString();
}

bool ULovenseToy::IsRunningTestCommand() {
	if (!this->IsValidToy()) return false;

	const TArray<TPair<FString, FTimerHandle>>& testTimersHandles = this->lovenseAdapter->GetToyTestTimerHandles();
	// If no test timers are running, we are definitely not running a test command, so return false.
	if (testTimersHandles.Num() <= 0) return false;

	// Look for our toy id and if found, return if the associated timer is running.
	for (const TPair<FString, FTimerHandle>& testTimerHandle : testTimersHandles) {
		if (testTimerHandle.Key != this->toyDescription.id) continue;
		return FLovenseManager::Get()->IsTimerRunning(testTimerHandle.Value);
	}

	// We couldn't find our toy id in the test timer handles, so we aren't running a test command.
	return false;
}

bool ULovenseToy::IsValidToy() {
	if (this->lovenseAdapter == NULL) {
		return false;
	}
	return ensureAlwaysMsgf(
		this->IsValidLowLevel() && !this->HasAnyFlags(EObjectFlags::RF_BeginDestroyed | EObjectFlags::RF_FinishDestroyed) && this->lovenseAdapter,
		TEXT("Invalid toy detected! Make sure you keep any cached toy objects up-to-date by subscribing to ULovenseEvents::onLovenseUpdatedToys.\nAffected toy: %s"),
		*this->toyDescription.ToString()
	);
}
