// 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()
{
    _last = 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(_last != result.GetActor())
        {
            if(_last)
            {
                interactableDeactivatedDelegate.Execute(_last, activatorType);
                _last = nullptr;
            }
            _activated = true;
            if(auto interactable = Cast<AInteractable>(result.GetActor()))
            {
                _last = 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(_last, activatorType);
            }
            _activated = false;
            _last = nullptr;
        }

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