using Godot;

namespace Cirno.Scripts.Interactables;

public partial class AreaTrigger : Area2D
{
    [Export] public Node2D Target { get; set; }

    [Export] public ActivationType ActivationType { get; set; } = Scripts.ActivationType.Toggle;
    
    [Export] public bool OneTime { get; set; }
    [Export] public bool DoNotActivateOnFirst { get; set; }

    private int _activations = 0;
    
    [Signal]
    public delegate void ActivatedEventHandler();

    private InteractionController _cachedPlayer;

    private bool Activate()
    {
        if (_activations == 0 && DoNotActivateOnFirst)
        {
            _activations++;
            return false;
        }
        
        if (OneTime && _activations > 0) return false;

        if (Target != null)
        {
            if (Target is not IActivable target)
            {
                GD.PrintErr($"Target {Target.Name} is not activable");
                return false;
            }
            target.Activate();
        }

        EmitSignal(nameof(Activated));
        
        _activations++;
        
        return true;

    }

    private void _on_area_entered(Area2D area)
    {
        if (area is not InteractionController player) return;
        if (player.Enabled)
        {
            Activate();
        }
        else
        {
            _cachedPlayer = player;
            _cachedPlayer.InteractionStarted += PlayerOnInteractionStarted;
        }
    }

    private void PlayerOnInteractionStarted()
    {
        Activate();
        if (_cachedPlayer != null)
        {
            _cachedPlayer.InteractionStarted -= PlayerOnInteractionStarted;
        }
    }
}