#include "KeyPickup.h"
#include "Components/BoxComponent.h"
#include "PaperSprite.h"
#include "PaperSpriteComponent.h"
#include "Engine/Engine.h"

AKeyPickup::AKeyPickup()
{
    PrimaryActorTick.bCanEverTick = true;

    CollisionBox = CreateDefaultSubobject<UBoxComponent>(TEXT("CollisionBox"));
    RootComponent = CollisionBox;

    KeySprite = CreateDefaultSubobject<UPaperSpriteComponent>(TEXT("KeySprite"));
    KeySprite->SetupAttachment(RootComponent);

    KeyColor = EKeyColor::Red;

    CollisionBox->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
    CollisionBox->SetCollisionResponseToAllChannels(ECR_Overlap);
    CollisionBox->OnComponentBeginOverlap.AddDynamic(this, &AKeyPickup::OnOverlapBegin);
}

void AKeyPickup::BeginPlay()
{
    Super::BeginPlay();

    InitialPosition = GetActorLocation();

    if (KeyColor == EKeyColor::Red)
    {
        UPaperSprite* RedKeySprite = Cast<UPaperSprite>(StaticLoadObject(UPaperSprite::StaticClass(), nullptr, TEXT("PaperSprite'/Game/Sprites/Objects/key_red_Sprite.key_red_Sprite'")));
        if (RedKeySprite)
        {
            KeySprite->SetSprite(RedKeySprite);
        }
    }
    else if (KeyColor == EKeyColor::Blue)
    {
        UPaperSprite* BlueKeySprite = Cast<UPaperSprite>(StaticLoadObject(UPaperSprite::StaticClass(), nullptr, TEXT("PaperSprite'/Game/Sprites/Objects/key_blue_Sprite.key_blue_Sprite'")));
        if (BlueKeySprite)
        {
            KeySprite->SetSprite(BlueKeySprite);
        }
    }
}

void AKeyPickup::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);

    float NewZ = InitialPosition.Z + FMath::Sin(GetWorld()->GetTimeSeconds() * HoverSpeed) * HoverAmplitude;

    if (bIsFollowingPlayer && PlayerReference)
    {
        FVector DesiredPosition = PlayerReference->GetActorLocation() + FollowOffset;
        DesiredPosition.Z += FMath::Sin(GetWorld()->GetTimeSeconds() * HoverSpeed) * HoverAmplitude;
        FVector NewLocation = FMath::VInterpTo(GetActorLocation(), DesiredPosition, DeltaTime, FollowSpeed);

        SetActorLocation(NewLocation);

        CheckPlayerTags();
    }
    else
    {
        FVector NewLocation = FVector(InitialPosition.X, InitialPosition.Y, NewZ);
        SetActorLocation(NewLocation);
    }
}

void AKeyPickup::CheckPlayerTags()
{
    if (!PlayerReference)
    {
        return;
    }

    if (KeyColor == EKeyColor::Red && !PlayerReference->ActorHasTag("HasRedKey"))
    {
        DestroyKey();
    }
    else if (KeyColor == EKeyColor::Blue && !PlayerReference->ActorHasTag("HasBlueKey"))
    {
        DestroyKey();
    }
}

void AKeyPickup::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor,
    UPrimitiveComponent* OtherComp, int32 OtherBodyIndex,
    bool bFromSweep, const FHitResult& SweepResult)
{
    if (OtherActor)
    {
        if (OtherActor->ActorHasTag("RedPlayer"))
        {
            if (KeyColor == EKeyColor::Red)
            {
               // GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, TEXT("Red Key collected by Red Player!"));

                PlayerReference = OtherActor;
                bIsFollowingPlayer = true;

                CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision);

                OtherActor->Tags.Add("HasRedKey");
            }
        }
        else if (OtherActor->ActorHasTag("BluePlayer"))
        {
            if (KeyColor == EKeyColor::Blue)
            {
                PlayerReference = OtherActor;
                bIsFollowingPlayer = true;

                CollisionBox->SetCollisionEnabled(ECollisionEnabled::NoCollision);

                OtherActor->Tags.Add("HasBlueKey");
            }
        }
    }
}

void AKeyPickup::DestroyKey()
{
    Destroy();
}
