#include "SkyPortalRunner.h"
#include "SkyPortalFigure.h"
#include "SkyPortalSubsystem.h"

FPortalStatusChecker::FPortalStatusChecker(UEngineSubsystem* InSubsystem, float InCheckInterval)
	: SkyPortalSubsystemRef(InSubsystem), CheckInterval(InCheckInterval), bShouldRun(true)
{
}

bool FPortalStatusChecker::Init()
{
	// Initialization logic, if necessary (e.g., logging)
	return true;
}

uint32 FPortalStatusChecker::Run()
{
	// Main loop of the thread, runs until Stop() is called
	while (bShouldRun)
	{
		// Check the portal status
		CheckPortalStatus();

		// Sleep for the specified interval
		FPlatformProcess::Sleep(CheckInterval);
	}

	return 0;  // Exit code for the thread
}

void FPortalStatusChecker::Stop()
{
	// Signal the thread to stop running
	bShouldRun = false;
}

void FPortalStatusChecker::Exit()
{
	// Cleanup after the thread has stopped
}

void FPortalStatusChecker::CheckPortalStatus()
{
	// Ensure the subsystem is valid
	if (SkyPortalSubsystemRef && Cast<USkyPortalSubsystem>(SkyPortalSubsystemRef))
	{
		USkyPortalSubsystem* subref = Cast<USkyPortalSubsystem>(SkyPortalSubsystemRef);
		USkyPortalIO* PortalHandleRef = subref->PortalHandle;
		UE_LOG(LogSkyportalIO, Verbose, TEXT("Check portal"));
		if (PortalHandleRef && PortalHandleRef->bPortalReady)
		{
			// Call the subsystem function to get portal status
			uint8* output = PortalHandleRef->Read();
			EPortalCommand CommandResponse = GetPortalCommandFromChar(output[0]);
			switch (CommandResponse)
			{
			case S:
				CurrentStatusData = ParsePortalStatus(output);

				//Send delegate when new informations are received
				if (OldStatusData != CurrentStatusData) {
					

					for (int i = 0; i < CurrentStatusData.StatusArray.Num(); i++) {
						if (CurrentStatusData.StatusArray[i] != OldStatusData.StatusArray[i]) {
							if (
								//!FalsePositive() //filter conflicting infos
								true) {
								//FigureDataBlock FigureData;
								switch (CurrentStatusData.StatusArray[i])
								{
								case EFigureStatus::NOT_PRESENT:
									subref->OnSkylanderRemoved.Broadcast(00, i);
									break;
								case EFigureStatus::PRESENT:
									//FigureData = ReadFigureBlocks(i);
									//subref->OnSkylanderAdded.Broadcast(GetFigureID(FigureData), i);
									break;
								case EFigureStatus::ADDED:
									//FigureData = ReadFigureBlocks(i);
									//subref->OnSkylanderAdded.Broadcast(GetFigureID(FigureData), i);
								case EFigureStatus::REMOVED:
									subref->OnSkylanderRemoved.Broadcast(00, i);
								}
							}
						}
					


					OldStatusData = CurrentStatusData;
					subref->StatusData = CurrentStatusData;
				}
				}
				break;
			default:
				return;
			}

			// Do something with the status (log, notify, etc.)
			UE_LOG(LogSkyportalIO, Verbose, TEXT("Portal Status:"));
		}

	}
}