// 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::Scan_Implementation()
{
    FHitResult result{};
    FVector startLocation = GetComponentLocation();
    FVector endLocation = startLocation + (GetComponentRotation().Vector() * scanDistance);

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

    static AInteractable* _last = nullptr;
    static bool _activated = false;
    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, 0.5f, 0, 0.5f);
#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, 0.5f, 10, 0.5f);
#endif // INTERACTABLE_ACTIVATOR_DEBUG
        }
    }