using Godot; using RailEnterprise.Client.App; using RailEnterprise.Client.Net; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Protocol.Client; using RailEnterprise.Protocol.Messages; using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client.Panels; /// /// Riquadro «Compravendita in proprio» del Mercato globale, quando il livello lo sblocca (ADR 0016): /// scelta della stazione propria, quantità, Compra, Vendi e Spedisci a un'altra stazione per la /// merce scelta nel pannello; giacenze del magazzino. Prezzi, disponibilità e giacenze arrivano dal /// server nel MarketReport: i comandi li ricalcola il server. I controlli restano gli stessi tra un /// quadro e l'altro, così le scelte non si perdono a ogni nuovo giorno. /// public sealed partial class TradeBox : VBoxContainer { /// Margine sul prezzo mostrato: si compra fino al 10 % sopra e si vende fino al 10 % sotto. private const double PriceTolerance = 0.10; private readonly GameSession _session; private readonly OptionButton _station = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) }; private readonly OptionButton _destination = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) }; private readonly SpinBox _quantity = new() { MinValue = 1, MaxValue = 100_000, Step = 1, Rounded = true, Value = 50, SizeFlagsHorizontal = SizeFlags.ExpandFill }; private readonly Label _good = UiTheme.Text("", 14, bold: true); private readonly Label _quote = UiTheme.Text("", 12, Palette.TextSecondary); private readonly Label _capacity = UiTheme.Text("", 12, Palette.TextSecondary); private readonly VBoxContainer _stock = PanelKit.Column(2); private readonly Label _status = UiTheme.Text("", 12); private readonly Button _buy = UiTheme.Primary(T("Compra")); private readonly Button _sell = new() { Text = T("Vendi") }; private readonly Button _ship = new() { Text = T("Spedisci a") }; private readonly List _stationIds = []; private readonly List _destinationIds = []; private MarketReport? _report; private int _goodId = -1; /// Esito di un comando: il pannello chiede subito un quadro aggiornato. public event Action? Traded; public TradeBox(GameSession session) { _session = session; AddThemeConstantOverride("separation", 8); foreach (var l in new[] { _quote, _capacity, _status }) l.AutowrapMode = TextServer.AutowrapMode.WordSmart; var station = PanelKit.Row(6); station.AddChild(UiTheme.Text(T("Stazione"), 13, Palette.TextSecondary)); station.AddChild(_station); AddChild(station); _station.ItemSelected += _ => Render(); AddChild(_good); AddChild(_quote); var qty = PanelKit.Row(6); qty.AddChild(UiTheme.Text(T("Quantità"), 13, Palette.TextSecondary)); qty.AddChild(_quantity); AddChild(qty); var trade = PanelKit.Row(6); _buy.SizeFlagsHorizontal = SizeFlags.ExpandFill; _sell.SizeFlagsHorizontal = SizeFlags.ExpandFill; _buy.TooltipText = T("Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato."); _sell.TooltipText = T("Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato."); _buy.Pressed += Buy; _sell.Pressed += Sell; trade.AddChild(_buy); trade.AddChild(_sell); AddChild(trade); var ship = PanelKit.Row(6); _ship.TooltipText = T("Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa."); _ship.Pressed += Ship; ship.AddChild(_ship); ship.AddChild(_destination); AddChild(ship); AddChild(_capacity); AddChild(UiTheme.Text(T("In magazzino"), 13, Palette.TextSecondary, bold: true)); AddChild(_stock); AddChild(_status); } /// Aggiorna stazioni, quotazioni e giacenze dal quadro ricevuto, per la merce scelta. public void Update(MarketReport report, int good) { _report = report; _goodId = good; var w = _session.World; int keep = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1; int keepTo = _destination.Selected >= 0 && _destination.Selected < _destinationIds.Count ? _destinationIds[_destination.Selected] : -1; _stationIds.Clear(); _station.Clear(); foreach (var h in report.Warehouses) { _stationIds.Add(h.Station); _station.AddItem(StationName(w, h.Station)); } int index = _stationIds.IndexOf(keep); if (_stationIds.Count > 0) _station.Select(index >= 0 ? index : 0); _destinationIds.Clear(); _destination.Clear(); foreach (var h in report.Warehouses) { _destinationIds.Add(h.Station); _destination.AddItem(StationName(w, h.Station)); } int to = _destinationIds.IndexOf(keepTo); if (_destinationIds.Count > 0) _destination.Select(to >= 0 ? to : Math.Min(1, _destinationIds.Count - 1)); Render(); } private WarehouseInfo? Current => _report is null || _station.Selected < 0 || _station.Selected >= _stationIds.Count ? null : _report.Warehouses.FirstOrDefault(h => h.Station == _stationIds[_station.Selected]); private WarehouseGoodInfo? CurrentGood => Current?.Goods.FirstOrDefault(g => g.Good == _goodId); private void Render() { var w = _session.World; foreach (var c in _stock.GetChildren()) c.QueueFree(); var house = Current; bool any = house is not null && _goodId >= 0 && _goodId < w.Data.Goods.Count; _buy.Disabled = _sell.Disabled = _ship.Disabled = !any; if (!any) { _good.Text = ""; _quote.Text = T("Costruisci una stazione per avere un magazzino dove comprare e vendere."); _capacity.Text = ""; return; } string unit = w.Data.Goods[_goodId].Unit; var g = CurrentGood; _good.Text = $"{T("Merce")}: {GoodName(w, _goodId)} · {T("in magazzino")} {g?.Units ?? 0} {unit}"; string buy = g is { BuyPrice: >= 0 } ? $"{T("Si compra a")} {Price(g.BuyPrice)}/{unit} ({Fmt.Number(g.BuyUnits, 0)} {unit} {T("disponibili")})" : T("Nessun produttore né hub nel bacino la vende"); string sell = g is { SellPrice: >= 0 } ? $"{T("si vende a")} {Price(g.SellPrice)}/{unit} ({Fmt.Number(g.SellUnits, 0)} {unit} {T("richieste")})" : T("nessun consumatore né hub nel bacino la compra"); _quote.Text = $"{buy}; {sell}. {T("Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.")}"; _buy.Disabled = g is not { BuyPrice: >= 0 }; _sell.Disabled = g is not { SellPrice: >= 0 } || g.Units <= 0; _ship.Disabled = (g?.Units ?? 0) <= 0 || _destinationIds.Count < 2; int used = house!.Goods.Sum(x => x.Units) + house.Incoming; _capacity.Text = $"{T("Magazzino")}: {Fmt.Number(used, 0)} / {Fmt.Number(house.Capacity, 0)} {T("unità")}" + (house.Incoming > 0 ? $" ({T("di cui")} {Fmt.Number(house.Incoming, 0)} {T("in arrivo")})" : ""); var held = house.Goods.Where(x => x.Units > 0).ToList(); if (held.Count == 0) _stock.AddChild(UiTheme.Text(T("Vuoto"), 12, Palette.TextSecondary)); foreach (var x in held) _stock.AddChild(PanelKit.Pair(GoodName(w, x.Good), PanelKit.Value($"{Fmt.Number(x.Units, 0)} {w.Data.Goods[x.Good].Unit}"))); } private void Buy() { if (Current is not { } house || CurrentGood is not { BuyPrice: >= 0 } g) return; var max = Money.FromCentsRounded(g.BuyPrice * (1 + PriceTolerance)); _session.Command(new BuyGoodsCommand(new StationId(house.Station), GoodId(), Units(), max), Result); } private void Sell() { if (Current is not { } house || CurrentGood is not { SellPrice: >= 0 } g) return; var min = Money.FromCentsRounded(g.SellPrice * (1 - PriceTolerance)); _session.Command(new SellGoodsCommand(new StationId(house.Station), GoodId(), Units(), min), Result); } private void Ship() { if (Current is not { } house || _destination.Selected < 0 || _destination.Selected >= _destinationIds.Count) return; int to = _destinationIds[_destination.Selected]; if (to == house.Station) { ShowStatus(T("Scegli una stazione di arrivo diversa da quella di partenza"), false); return; } _session.Command(new ShipGoodsCommand(new StationId(house.Station), new StationId(to), GoodId(), Units()), Result); } private string GoodId() => _session.World.Data.Goods[_goodId].Id; private int Units() => (int)Math.Max(1, Math.Round(_quantity.Value)); private void Result(CommandResultMessage r) { ShowStatus(r.Message, r.Ok); Traded?.Invoke(); } private void ShowStatus(string text, bool ok) { _status.Text = text; _status.AddThemeColorOverride("font_color", ok ? Palette.Ok : Palette.Danger); } private static string StationName(ClientWorld w, int station) => w.Stations.TryGetValue(station, out var s) ? s.Name : $"{T("Stazione")} {station}"; private static string GoodName(ClientWorld w, int good) { var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)]; return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt; } private static string Price(double cents) => Money.FromCentsRounded(cents).ToString(); }