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


#include "GadgetManager.h"

// Sets default values
AGadgetManager::AGadgetManager()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

}

// Called when the game starts or when spawned
void AGadgetManager::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void AGadgetManager::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

}

void AGadgetManager::SpawnGadgetsOnBeginPlay(USceneComponent* PlayersCameraComponent)
{
	if (IsValid(ReconClass)) SpawnGadget(ReconClass, PlayersCameraComponent);
	if (IsValid(CombatClass)) SpawnGadget(CombatClass, PlayersCameraComponent);
}

void AGadgetManager::SpawnGadget(TSubclassOf<AGadgetBase> GadgetClass, USceneComponent* PlayersCameraComponent)
{
	FActorSpawnParameters SpawnParams;
	SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
	const FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget, true);

	AActor* SpawnedActor = GetWorld()->SpawnActor<AActor>(GadgetClass, GetActorLocation(), GetActorRotation(), SpawnParams);
	
	if (SpawnedActor->IsA(AReconGadget::StaticClass()))
	{
		if (IsValid(ReconGadget)) ReconGadget->Destroy();
		ReconGadget = Cast<AReconGadget>(SpawnedActor);
	}
	else if (SpawnedActor->IsA(ACombatGadget::StaticClass()))
	{
		if (IsValid(CombatGadget)) CombatGadget->Destroy();
		CombatGadget = Cast<ACombatGadget>(SpawnedActor);
	}
	else UE_LOG(LogTemp, Fatal, TEXT("Passed sub class of gadget base is neither a combat or recon gadget, check the gadget class you're passing through or contact Rafal"));

	AGadgetBase* BaseGadget = Cast<AGadgetBase>(SpawnedActor);
	BaseGadget->AttachToComponent(PlayersCameraComponent, AttachmentRules);
	BaseGadget->SetActorRelativeLocation(BaseGadget->GetUnequippedOffset());
	BaseGadget->SetActorRelativeRotation(BaseGadget->GetGadgetSpawnRotation());
}

