using Godot;
using System;
using System.Linq;
using Cirno.Scripts.Resources;

public partial class StatusMenu : PanelContainer
{
    [Export] public StringName HealthExpansionName { get; private set; }
    
    [Export] public StringName ShieldExpansionName { get; private set; }
    
    //[Export] public ItemsDatabase ItemsDatabase { get; private set; }

    [Export] public Button HealthExpansionCounter { get; private set; }
    
    [Export] public Button ShieldExpansionCounter { get; private set; }
    
    [Export] public Button WeaponButton { get; private set; }
    
    public override void _Ready()
    {
        CallDeferred(MethodName.InitializeDeferred);
    }

    public override void _ExitTree()
    {
        InventoryManager.Instance.ItemAdded -= InstanceOnItemAdded;
    }

    private void InitializeDeferred()
    {
        var healthExpansions = InventoryManager.Instance.GetItemCount(HealthExpansionName);
        var shieldExpansions = InventoryManager.Instance.GetItemCount(ShieldExpansionName);

        HealthExpansionCounter.Text = $"x{healthExpansions}";
        ShieldExpansionCounter.Text = $"x{shieldExpansions}";
        
        InventoryManager.Instance.ItemAdded += InstanceOnItemAdded;
        
        InventoryManager.Instance.WeaponEquip += InstanceOnWeaponEquip;
    }

    private void InstanceOnWeaponEquip(string itemKey)
    {
        //var weaponData = ItemsDatabase.GetLootItem(itemKey);

        var succ = InventoryManager.Instance.TryGetItem(itemKey, out var item);
        if (!succ)
        {
            GD.Print($"Could not get item {itemKey}");
            return;
        }

        WeaponButton.Text = item.Item.ShortName;
        WeaponButton.Icon = item.Item.InventorySprite;
    }

    private void InstanceOnItemAdded(LootItem item, int currentamount)
    {
        if (item.ItemKey == HealthExpansionName)
        {
            HealthExpansionCounter.Text = $"x{currentamount}";
        }
        else if (item.ItemKey == ShieldExpansionName)
        {
            ShieldExpansionCounter.Text = $"x{currentamount}";
        }
    }
}
