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


#include "InteractNPC.h"
#include "DialogueNPC.h"
#include "Camera/CameraComponent.h"
#include "the_twilight_abyss/PlayerTemp/TempCharacter.h"


// Sets default values for this component's properties
UInteractNPC::UInteractNPC()
{
	// Set this component to be initialized when the game starts, and to be ticked every frame.  You can turn these features
	// off to improve performance if you don't need them.
	PrimaryComponentTick.bCanEverTick = true;

	// ...
}


// Called when the game starts
void UInteractNPC::BeginPlay()
{
	Super::BeginPlay();

	// ...
	
}


// Called every frame
void UInteractNPC::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

	// ...
}

void UInteractNPC::Interact()
{
	FVector Start = Cast<UCameraComponent>(GetOwner()->FindComponentByClass<UCameraComponent>())->GetComponentLocation();
	FVector End = GetOwner()->GetActorForwardVector() * 300.0f + Start;
	FCollisionQueryParams CollisionParams;
	CollisionParams.AddIgnoredActor(GetOwner());
	if (FHitResult HitResult; GetWorld()->LineTraceSingleByChannel(HitResult, Start, End, ECC_Pawn, CollisionParams))
	{
		//UE_LOG(LogTemp, Warning, TEXT("Hit: %s"), *HitResult.GetActor()->GetName());
		if (HitResult.GetActor()->Tags.Contains("NPC"))
		{
			//DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 5.0f, 0, 10.0f);
			if (Cast<ATempCharacter>(GetOwner())->bShopKeeperText) return;
			if (Cast<ATurnBaseCombatV2>(GetWorld()->GetGameState())->bIsInCombat) return;
			UDialogueNPC* DialogueNPC = HitResult.GetActor()->FindComponentByClass<UDialogueNPC>();
			if (DialogueNPC->bIsInDialogue)
			{
				DialogueNPC->NextDialogue();
				return;
			}
			DialogueNPC->StartDialogue();
		}
		//DrawDebugLine(GetWorld(), Start, End, FColor::Red, false, 5.0f, 0, 10.0f);
	}
}

void UInteractNPC::EndInteract()
{
	FVector Start = Cast<UCameraComponent>(GetOwner()->FindComponentByClass<UCameraComponent>())->GetComponentLocation();
	FVector End = GetOwner()->GetActorForwardVector() * 300.0f + Start;
	FCollisionQueryParams CollisionParams;
	CollisionParams.AddIgnoredActor(GetOwner());
	if (FHitResult HitResult; GetWorld()->LineTraceSingleByChannel(HitResult, Start, End, ECC_Pawn, CollisionParams))
	{
		//UE_LOG(LogTemp, Warning, TEXT("Hit: %s"), *HitResult.GetActor()->GetName());
		if (HitResult.GetActor()->Tags.Contains("NPC"))
		{
			//DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 5.0f, 0, 10.0f);
			UDialogueNPC* DialogueNPC = HitResult.GetActor()->FindComponentByClass<UDialogueNPC>();
			DialogueNPC->EndDialogue();
		}
		//DrawDebugLine(GetWorld(), Start, End, FColor::Red, false, 5.0f, 0, 10.0f);
	}
}