using Godot;
using Newlon.Components.Plants;
using Newlon.Components.Level;

namespace Newlon.Components.GUI;

public partial class ShovelButton : TextureButton
{
    [Export] private PackedScene particles;
    private void OnFocusExited()
    {
        ButtonPressed = false;
    }
    public override void _Toggled(bool toggledOn)
    {
        Cursor.Instance.shovel = toggledOn;
        Cursor.Instance.UpdateCursor();
    }

    public override void _Input(InputEvent @event)
    {

        if (@event.IsActionPressed("primary_action") && ButtonPressed)
        {
            var checkedPosition = (PoolContainer.Instance.Plants.GetGlobalMousePosition() / Utility.Tile).Ceil() * Utility.Tile - new Vector2(20, 14);

            for (int i = Utility.LayersCount - 1; i >= 0; i--)
            {
                if (PoolContainer.Instance.EntityField[i].TryGetValue(checkedPosition, out var entity) && entity is RuntimePlantData plantData)
                {
                    plantData.Kill();

                    PoolContainer.Instance.SpawnParticles(particles, plantData.GlobalPosition + Vector2.Down * Utility.TileHeight / 2.0f);

                    break;
                }
            }
            ButtonPressed = false;
        }
        if (@event.IsActionPressed("cancel_plant") && ButtonPressed)
        {
            ButtonPressed = false;
        }
    }
}
