using Godot;
using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.Progression;
using Mr.BrickAdventures.scripts.Resources;
namespace Mr.BrickAdventures.scripts.UI;
///
/// One buy/upgrade button in the marketplace.
///
///
/// Reads the owned level from the Playthrough and the costs from the authored upgrade table — the split
/// SkillData.Level used to blur. It also listens to rather
/// than to a signal on a component it had to locate by node path on the player.
///
public partial class MarketplaceButton : Button
{
[Export] public SkillData Data { get; set; }
[Export] public Texture2D UnlockedSkillIcon { get; set; }
[Export] public Texture2D LockedSkillIcon { get; set; }
[Export] public Container SkillLevelContainer { get; set; }
private static ProgressionRoot Progression => ProgressionRoot.Instance;
public override void _Ready()
{
if (EventBus.Instance != null)
{
EventBus.Instance.SkillSetChanged += UpdateButtonState;
EventBus.Instance.CoinsChanged += OnCoinsChanged;
}
UpdateButtonState();
}
public override void _ExitTree()
{
if (EventBus.Instance != null)
{
EventBus.Instance.SkillSetChanged -= UpdateButtonState;
EventBus.Instance.CoinsChanged -= OnCoinsChanged;
}
}
private void OnCoinsChanged(int totalCoins) => UpdateButtonState();
/// The level the player owns this skill at, or 0 when they do not own it.
private int OwnedLevel()
{
if (Data == null || Progression == null || string.IsNullOrWhiteSpace(Data.Name)) return 0;
return Progression.LevelOf(SkillId.Of(Data.Name))?.Value ?? 0;
}
private void UpdateButtonState()
{
if (Data == null || Data.Upgrades.Count == 0)
{
// No authored upgrades means it cannot be bought at any price.
Visible = false;
return;
}
var owned = OwnedLevel();
for (var i = 0; i < SkillLevelContainer.GetChildCount(); i++)
SkillLevelContainer.GetChild(i).QueueFree();
for (var i = 0; i < Data.MaxLevel; i++)
{
SkillLevelContainer.AddChild(new TextureRect
{
Texture = i < owned ? UnlockedSkillIcon : LockedSkillIcon,
ExpandMode = TextureRect.ExpandModeEnum.FitWidthProportional,
});
}
if (owned >= Data.MaxLevel)
{
Text = $"{Tr(Data.Name)} (MAX)";
Disabled = true;
return;
}
// Upgrades[n] is the cost to reach level n + 1, so the next level costs Upgrades[owned].
Text = $"{Tr(Data.Name)} ({Data.Upgrades[owned].Cost})";
Disabled = false;
}
}