// Project Lab - NHTV Igad

#include "UnrealProject.h"
#include "NetworkDoor.h"

#include "NetworkCharacter.h"
#include "NetworkSwitchComponent.h"
#include "CreatureSpawn.h"
#include "NetworkSwitch.h"



ANetworkSwitch::ANetworkSwitch()
{
	cooldown = m_elapsedTime = 0.0f;
	cubeCollider = CreateDefaultSubobject<UBoxComponent>(TEXT("Cube"));
	cubeCollider->SetCollisionProfileName(TEXT("BlockAll"));
	RootComponent = cubeCollider;

	meshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Static Mesh"));
	meshComponent->AttachTo(RootComponent);

	visualizerComponent = CreateDefaultSubobject<UNetworkSwitchComponent>(TEXT("Visualizer"));
	visualizerComponent->AttachTo(RootComponent);

	isSwitchClosed = false;

	toggles = false;
}

void ANetworkSwitch::BeginPlay()
{
	Super::BeginPlay();
	m_elapsedTime = cooldown;

	if (Role != ROLE_Authority)
		return;

	// Init the door states
	if (!toggles)
	{
		for (int32 i = 0; i < doorsToOpen.Num(); i++)
		{
			if (doorsToOpen[i])
				doorsToOpen[i]->SetDoorState(isSwitchClosed);
		}
	}
}

void ANetworkSwitch::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// Animate the switch (must be replaced with an actual animated mesh in future)
	meshComponent->SetRelativeRotation(FRotator(isSwitchClosed ? 30 : -30, 0, 0));

	if (Role != ROLE_Authority)
		return;

	if (cooldown > 0)
		m_elapsedTime += DeltaTime;
}

void ANetworkSwitch::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(ANetworkSwitch, isSwitchClosed);
}

void ANetworkSwitch::Toggle()
{
	check(Role == ROLE_Authority);

	if (m_elapsedTime < cooldown)
		return;

	m_elapsedTime = 0;
	isSwitchClosed = !isSwitchClosed;

	// Toggle all linked doors
	for (int32 i = 0; i < doorsToOpen.Num(); i++)
	{
		if (doorsToOpen[i])
		{
			if (toggles)
				doorsToOpen[i]->ToggleDoor();
			else
				doorsToOpen[i]->SetDoorState(isSwitchClosed);
		}
	}
}