using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Common;
using RailEnterprise.Core.Economy;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
///
/// Tooltip «perché» comune (F6, ADR 0024): sopra un valore dei pannelli, dopo un breve ritardo, mostra la
/// spiegazione calcolata dal server (titolo, valore, formula, termini con i valori di oggi, note) nello stile
/// della palette 05. Il client non calcola nulla: se la spiegazione manca o è di un giorno passato la chiede
/// (RequestDetail con DetailKind.Explain) e intanto mostra «in arrivo…». Un solo tooltip per schermata, su
/// un suo CanvasLayer sopra l'interfaccia; i pannelli lo agganciano con .
///
public partial class WhyTooltip : PanelContainer
{
/// Tooltip della schermata di gioco (null fuori partita: gli agganci restano muti).
public static WhyTooltip? Instance { get; private set; }
/// Ritardo prima dell'apertura (secondi).
private const double OpenDelay = 0.45;
/// Intervallo minimo tra due richieste della stessa spiegazione (secondi).
private const double RequestInterval = 1.0;
private const float MaxWidth = 440;
private readonly GameSession _session;
private readonly VBoxContainer _body = new();
private Control? _hover;
private Func? _target;
private string _hint = "";
private (byte Subject, int Target, int Arg) _key;
private double _wait;
private double _sinceRequest = double.MaxValue;
private int _shownVersion = -1;
private ExplanationReport? _shown;
public WhyTooltip(GameSession session)
{
_session = session;
Visible = false;
MouseFilter = MouseFilterEnum.Ignore;
TopLevel = true;
AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Amber, 8, 14));
_body.AddThemeConstantOverride("separation", 6);
_body.MouseFilter = MouseFilterEnum.Ignore;
AddChild(_body);
}
public override void _EnterTree() => Instance = this;
public override void _ExitTree()
{
if (Instance == this) Instance = null;
}
///
/// Aggancia il tooltip a un controllo: al passaggio del mouse chiede a quale valore
/// spiegare (null: nessuna spiegazione per ora). Il controllo riceve il mouse senza fermare i clic dei genitori.
/// (già tradotto) compare in fondo, per esempio che un clic apre un pannello.
///
public static void Attach(Control control, Func target, string hint = "")
{
if (control.MouseFilter == MouseFilterEnum.Ignore) control.MouseFilter = MouseFilterEnum.Pass;
control.MouseEntered += () => Instance?.Enter(control, target, hint);
control.MouseExited += () => Instance?.Leave(control);
}
private void Enter(Control control, Func target, string hint)
{
_hover = control;
_target = target;
_hint = hint;
_wait = 0;
_shown = null;
_shownVersion = -1;
Visible = false;
}
private void Leave(Control control)
{
if (_hover != control) return;
_hover = null;
_target = null;
Visible = false;
}
public override void _Process(double delta)
{
if (_hover is null || _target is null) return;
if (!IsInstanceValid(_hover) || !_hover.IsVisibleInTree())
{
Leave(_hover);
return;
}
_wait += delta;
_sinceRequest += delta;
if (_wait < OpenDelay) return;
if (_target() is not { Subject: not ExplainSubject.None } t)
{
Visible = false;
return;
}
var key = ((byte)t.Subject, t.A, t.B);
var w = _session.World;
if (key != _key)
{
_key = key;
_sinceRequest = double.MaxValue;
_shown = null;
_shownVersion = -1;
}
var e = w.Explanations.GetValueOrDefault(key);
// una spiegazione di un giorno passato si mostra finché arriva quella di oggi
bool stale = e is null || e.Day < Fmt.Today(w);
if (stale && _sinceRequest >= RequestInterval && _session.IsOpen)
{
_sinceRequest = 0;
_session.Send(new RequestDetail { Kind = DetailKind.Explain, Target = t.A, Subject = (byte)t.Subject, Arg = t.B });
}
if (!ReferenceEquals(e, _shown) || _shownVersion < 0)
{
_shown = e;
_shownVersion = w.ExplanationVersion;
Rebuild(w, e, t);
}
Visible = true;
Place();
}
/// Vicino al puntatore, in basso a destra, dentro la finestra.
private void Place()
{
var view = GetViewportRect().Size;
var mouse = GetViewport().GetMousePosition();
var size = GetCombinedMinimumSize();
Size = size;
float x = mouse.X + 18, y = mouse.Y + 22;
if (x + size.X > view.X - 8) x = Math.Max(8, mouse.X - size.X - 12);
if (y + size.Y > view.Y - 8) y = Math.Max(8, mouse.Y - size.Y - 12);
Position = new Vector2(x, y);
}
private void Rebuild(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
{
foreach (var child in _body.GetChildren()) child.QueueFree();
Content(w, e, t);
if (_hint.Length > 0) _body.AddChild(UiTheme.Text(_hint, 12, Palette.Amber));
}
private void Content(Protocol.Client.ClientWorld w, ExplanationReport? e, ExplainTarget t)
{
if (e is null)
{
_body.AddChild(UiTheme.Text(T("Perché questo valore"), 13, Palette.TextSecondary, bold: true));
_body.AddChild(UiTheme.Text(T("in arrivo…"), 14, Palette.TextSecondary));
return;
}
var head = UiTheme.Text(e.Title.Length > 0 ? T(e.Title) : T("Perché questo valore"), 15, Palette.AmberLight, bold: true);
_body.AddChild(head);
string name = SubjectName(w, e, t);
if (name.Length > 0) _body.AddChild(Wrapped(name, 13, Palette.TextSecondary));
if (!e.Available)
{
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 13, Palette.TextSecondary));
return;
}
string value = Format(e.Value, e.Unit, (ExplainSubject)e.Subject);
_body.AddChild(UiTheme.TitleLabel(e.ValueText.Length > 0 ? $"{e.ValueText} ({value})" : value, 28, Palette.Text));
if (e.Formula.Length > 0)
{
var box = new PanelContainer { MouseFilter = MouseFilterEnum.Ignore };
box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 6, 10));
box.AddChild(Wrapped(T(e.Formula), 13, Palette.Text));
_body.AddChild(box);
}
if (e.Terms.Count > 0)
{
var grid = new GridContainer { Columns = 3, MouseFilter = MouseFilterEnum.Ignore };
grid.AddThemeConstantOverride("h_separation", 10);
grid.AddThemeConstantOverride("v_separation", 3);
foreach (var term in e.Terms)
{
// i simboli che sono parole (soglia, quota, prezzo…) si traducono, le lettere restano come nella formula
var symbol = UiTheme.Text(term.Symbol.Length >= 3 ? T(term.Symbol) : term.Symbol, 13, Palette.Amber, bold: true);
var label = UiTheme.Text(T(term.Label), 13, Palette.TextSecondary);
label.SizeFlagsHorizontal = SizeFlags.ExpandFill;
var v = UiTheme.Text(term.Unit == (byte)ExplainUnit.Text ? Translated(term.Text) : Format(term.Value, term.Unit, (ExplainSubject)e.Subject), 13, bold: true);
v.HorizontalAlignment = HorizontalAlignment.Right;
foreach (var l in new[] { symbol, label, v }) l.MouseFilter = MouseFilterEnum.Ignore;
grid.AddChild(symbol);
grid.AddChild(label);
grid.AddChild(v);
}
_body.AddChild(grid);
}
foreach (var n in e.Notes) _body.AddChild(Wrapped(T(n), 12, Palette.TextSecondary));
if (e.Day < Fmt.Today(w)) _body.AddChild(UiTheme.Text(T("aggiornamento in arrivo…"), 12, Palette.TextSecondary));
}
/// Nome dell'oggetto: i beni nella lingua dell'interfaccia, il resto com'è (nomi propri dal server).
private static string SubjectName(Protocol.Client.ClientWorld w, ExplanationReport e, ExplainTarget t)
{
bool en = TranslationServer.GetLocale().StartsWith("en");
string Good(int g) => g >= 0 && g < w.Data.Goods.Count ? (en ? w.Data.Goods[g].NameEn : w.Data.Goods[g].NameIt) : "";
return t.Subject switch
{
ExplainSubject.GlobalPrice => Good(t.A),
ExplainSubject.LocalPrice => w.Industries.TryGetValue(t.B, out var ind) ? $"{Good(t.A)} · {ind.Name}" : e.Name,
_ => e.Name,
};
}
/// Testi dei valori testuali: componenti dei veicoli tradotti, il resto (rating, nomi, anni) com'è.
private static string Translated(string text) => text switch
{
"engine" => T("motore"),
"brakes" => T("freni"),
"body" => T("cassa"),
_ => text,
};
/// Formato del valore secondo l'unità, con gli arrotondamenti dei pannelli.
public static string Format(double v, byte unit, ExplainSubject subject)
{
if (double.IsPositiveInfinity(v)) return "∞";
if (double.IsNegativeInfinity(v)) return "−∞";
if (double.IsNaN(v)) return "—";
return (ExplainUnit)unit switch
{
ExplainUnit.Money => new Money((long)Math.Round(v)).ToString(),
ExplainUnit.Price => Money.FromCentsRounded(v).ToString(),
// l'avanzamento si legge per difetto come nella barra superiore e nella scalata (ADR 0018)
ExplainUnit.Percent => subject == ExplainSubject.TierProgress ? Fmt.Progress(v) : Fmt.Pct(v, Math.Abs(v) < 0.01 && v != 0 ? 3 : 1),
ExplainUnit.Factor => "× " + Fmt.Number(v, 3),
ExplainUnit.Km => Fmt.Number(v, 1) + " km",
ExplainUnit.Days => Fmt.Number(v, 1) + " " + T("giorni"),
ExplainUnit.Units => Fmt.Number(v, Math.Abs(v - Math.Round(v)) < 1e-9 ? 0 : 1),
ExplainUnit.Condition => Fmt.Number(v, 1),
ExplainUnit.Years => Fmt.Number(v, 1) + " " + T("anni"),
_ => Fmt.Number(v, Math.Abs(v) < 0.01 && v != 0 ? 5 : 3),
};
}
private static Label Wrapped(string text, int size, Color color)
{
var l = UiTheme.Text(text, size, color);
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
l.CustomMinimumSize = new Vector2(MaxWidth - 40, 0);
l.MouseFilter = MouseFilterEnum.Ignore;
return l;
}
}