using Cirno.Scripts.Interactables;
using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.Actors;

[Tool]
public partial class ItemMarker : Marker2D
{
    private LootItem _item;
    
    [Export]
    public LootItem Item
    {
        get => _item;
        set
        {
            _item = value;
            if (Engine.IsEditorHint())
            {
                QueueRedraw();
            }
        }
    }

    [Export] public bool AutoSpawn { get; set; } = false;
    
    [ExportToolButton("Update Icon")] public Callable RedrawButton => Callable.From(Redraw);
    
    public override void _Draw()
    {
        if (!Engine.IsEditorHint()) return;
        if (Item is null) return;
        if (Item.InventorySprite is null) return;
        
        DrawTexture(Item.InventorySprite, - new Vector2(Item.InventorySprite.GetWidth() / 2f, Item.InventorySprite.GetHeight() / 2f));
    }

    private void Redraw()
    {
        QueueRedraw();
    }

    public override void _Ready()
    {
        if (Engine.IsEditorHint()) return;
        if (AutoSpawn)
        {
            Spawn(true);
        }
    }

    public ItemPickup Spawn(bool deleteMarker)
    {
        if (Engine.IsEditorHint()) return null;
        if (Item is null) return null;

        if (deleteMarker)
        {
            this.QueueFree();
        }
        
        return Item.Spawn(this);
    }
}