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

namespace Cirno.Scripts.UI;

public partial class VendingMachineUi : CanvasLayer
{
    [Export] public Label MoneyLabel { get; private set; }
    [Export] public Container ItemsContainer { get; private set; }
    
    public VendingMachine Machine { get; set; }
    
    public LootItem[] Items { get; set; } = new LootItem[3];

    public override void _Ready()
    {
        FillItems();
    }

    private void FillItems()
    {
        var buttons = ItemsContainer.GetChildren().Cast<Button>().ToList();

        int i = 0;
        foreach (var button in buttons)
        {
            var item = Items[i];
            if (item is null)
            {
                button.Disabled = true;
                button.Icon = new PlaceholderTexture2D() { Size = new Vector2(16, 16) };
                button.Text = "Sold Out";
                i++;
                continue;
            }

            button.Icon = item.InventorySprite;
            button.Text = $"{item.ShortName} ({item.Price})";
            
            button.Pressed += () => ButtonOnPressed(item);
            
            i++;
        }

        var moneyAmount = InventoryManager.Instance.GetItemCount("CREDITS");
        
        MoneyLabel.Text = $"{moneyAmount}";
        
        buttons.First().GrabFocus();
    }

    private void ButtonOnPressed(LootItem item)
    {
        var moneyAmount = InventoryManager.Instance.GetItemCount("CREDITS");

        if (moneyAmount >= item.Price)
        {
            // Buy!
            InventoryManager.Instance.RemoveItem("CREDITS", item.Price);
            InventoryManager.Instance.AddItem(item);

            if (!Machine.Infinite)
            {
                Machine.Items.Remove(item);
            }
            
            Exit();
        }
    }

    private void Exit()
    {
        GD.Print("Closing");
        GameManager.Instance.ChangeState(GameState.Playing);
        QueueFree();
    }
}