using Godot;

namespace AceFieldNewHorizon.Scripts.System;

public partial class ItemPickup : Node2D
{
    public const string PickupGroupName = "ItemPickupTarget";

    [Export] public string ItemId { get; set; } = "";
    [Export] public int Quantity { get; set; } = 1;
    [Export] public bool Infinite { get; set; } = false;

    private Sprite2D _sprite;

    // Called when the node enters the scene tree
    public override void _Ready()
    {
        var area = GetNode<Area2D>("Area2D");
        area.BodyEntered += OnBodyEntered;

        _sprite = GetNode<Sprite2D>("Sprite2D");
        UpdateTexture();
    }

    private void UpdateTexture()
    {
        var file = FileAccess.Open("res://Data/ItemTextures.json", FileAccess.ModeFlags.Read);
        if (file == null)
        {
            GD.PrintErr("Failed to open ItemTextures.json");
            return;
        }

        var text = file.GetAsText();
        file.Close();

        var json = new Json();
        var err = json.Parse(text);
        if (err != Error.Ok)
        {
            GD.PrintErr(json.GetErrorMessage());
            return;
        }

        var dict = json.Data.AsGodotDictionary();
        if (!dict.TryGetValue(ItemId, out var value))
            return;

        var texturePath = value.AsString();
        if (string.IsNullOrEmpty(texturePath))
            return;

        var texture = GD.Load<Texture2D>(texturePath);
        if (texture == null)
            return;

        _sprite.Texture = texture;
    }

    private void OnBodyEntered(Node body)
    {
        if (body.IsInGroup(PickupGroupName))
        {
            if (body.HasMethod("AddItem"))
                body.Call("AddItem", ItemId, Quantity);

            if (!Infinite)
                QueueFree(); // remove the pickup from the world
        }
    }
}