#include "Player/InteractionComponent.h"

UInteractionComponent::UInteractionComponent()
{
	PrimaryComponentTick.bCanEverTick = true;
}


void UInteractionComponent::BeginPlay()
{
	Super::BeginPlay();
}


void UInteractionComponent::CheckForInteractable()
{
    AActor* Owner = GetOwner();
    APawn* PawnOwner = Cast<APawn>(Owner);

    if (!PawnOwner || !PawnOwner->GetController()) return;

    FVector ViewLocation;
    FRotator ViewRotation;
    PawnOwner->GetController()->GetPlayerViewPoint(ViewLocation, ViewRotation);
        
    FVector ForwardVector = ViewRotation.Vector();
    FVector LineEnd = ViewLocation + (ForwardVector * InteractionDistance);

    FHitResult HitResult;
    FCollisionQueryParams QueryParams;
    QueryParams.AddIgnoredActor(Owner);

    bool bHit = GetWorld()->LineTraceSingleByChannel(HitResult, ViewLocation, LineEnd, ECC_Visibility, QueryParams);

    if (bHit && HitResult.GetActor() && HitResult.GetActor()->Implements<UInteractable>())
    {
        InteractedActor = HitResult.GetActor();
    }
    else
    {
        InteractedActor = nullptr;
    }

    if (bShowDebugLine)
        DrawDebugLine(GetWorld(), ViewLocation, LineEnd, FColor::Red, false, 1.0f, 0, 1.0f);
}


void UInteractionComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
	Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
    CheckForInteractable();
}

