// Oleg Petruny proprietary.

#include "RaycastInteractableActivator.h"

#include "DrawDebugHelpers.h" 
#include "Engine/World.h"

URaycastInteractableActivator::URaycastInteractableActivator(const FObjectInitializer& ObjectInitializer)
    : UInteractableActivator(ObjectInitializer)
{
    activatorType = EActivatorType::Use;
}

void URaycastInteractableActivator::Rescan_Implementation()
{
    lastInteractable = nullptr;
}

void URaycastInteractableActivator::Scan_Implementation()
{
    FHitResult result;
    FVector startLocation = GetComponentLocation();
    FVector endLocation = startLocation + (GetComponentRotation().Vector() * scanDistance);

    world->LineTraceSingleByChannel(
        result,
        startLocation,
        endLocation,
        collisionChannel
    );

    if(result.bBlockingHit)
    {
        if(lastInteractable != result.GetActor())
        {
            if(lastInteractable)
            {
                interactableDeactivatedDelegate.Execute(lastInteractable, activatorType);
                lastInteractable = nullptr;
            }
            activated = true;
            if(auto interactable = Cast<AInteractable>(result.GetActor()))
            {
                lastInteractable = interactable;
                if(interactableActivatedDelegate.IsBound())
                {
                    interactableActivatedDelegate.Execute(interactable, activatorType);
                }
            }
        }

#ifdef INTERACTABLE_ACTIVATOR_DEBUG
        DrawDebugLine(GetWorld(), startLocation, endLocation, FColor::Green, false, PrimaryComponentTick.TickInterval, 0, 0.1f);
#endif // INTERACTABLE_ACTIVATOR_DEBUG
    }
    else
    {
        if(activated)
        {
            if(interactableDeactivatedDelegate.IsBound())
            {
                interactableDeactivatedDelegate.Execute(lastInteractable, activatorType);
            }
            activated = false;
            lastInteractable = nullptr;
        }

#ifdef INTERACTABLE_ACTIVATOR_DEBUG
        DrawDebugLine(GetWorld(), startLocation, endLocation, FColor::Red, false, PrimaryComponentTick.TickInterval, 10, 0.1f);
#endif // INTERACTABLE_ACTIVATOR_DEBUG
    }
}