using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Core.Data;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
///
/// Testi degli eventi del mondo in corso (ADR 0017) per l'elenco «Eventi in corso», le schede delle
/// entità e il Mercato globale. Solo presentazione: i valori dei moltiplicatori arrivano dal server.
///
public static class WorldEventText
{
// codici di EntityKind del protocollo
private const byte TownEntity = 1, IndustryEntity = 2, DepotEntity = 7;
private static bool English => TranslationServer.GetLocale().StartsWith("en");
public static WorldEventDef? Def(ClientWorld w, WorldEventInfo e) => w.Data.Events.Events.FirstOrDefault(d => d.Id == e.Type);
/// Nome del tipo di evento nella lingua dell'interfaccia.
public static string Name(ClientWorld w, WorldEventInfo e) =>
Def(w, e) is { } d ? (English ? d.NameEn : d.NameIt) : e.Type;
/// Nome dell'entità coinvolta (città, industria, deposito).
public static string Target(ClientWorld w, WorldEventInfo e) => e.Entity switch
{
TownEntity => w.Towns.TryGetValue(e.EntityIndex, out var t) ? t.Name : "?",
IndustryEntity => w.Industries.TryGetValue(e.EntityIndex, out var i) ? i.Name : "?",
DepotEntity => w.Depots.TryGetValue(e.EntityIndex, out var d) ? d.Name : "?",
_ => "?",
};
public static string GoodName(ClientWorld w, int good)
{
if (good < 0 || good >= w.Data.Goods.Count) return "";
var def = w.Data.Goods[good];
return English ? def.NameEn : def.NameIt;
}
/// Effetti con il loro valore («Produzione 25%», «Velocità dei treni 80%»).
public static string Effects(ClientWorld w, WorldEventInfo e)
{
var def = Def(w, e);
if (def is null) return "";
var parts = new List();
for (int i = 0; i < def.Effects.Count && i < e.Effects.Length; i++)
{
string label = def.Effects[i].Kind switch
{
EventEffectKind.IndustryCapacity => T("Capacità produttiva"),
EventEffectKind.TownDemand => T("Consumi della città"),
EventEffectKind.GoodDemand => $"{T("Domanda di")} {GoodName(w, e.Good).ToLowerInvariant()}",
EventEffectKind.Attendance => T("Presenze al lavoro"),
EventEffectKind.TrainSpeed => T("Velocità dei treni"),
EventEffectKind.TrackWear => T("Usura dei binari"),
_ => "",
};
parts.Add($"{label} {Fmt.Pct(e.Effects[i], 0)}");
}
return string.Join(" · ", parts);
}
/// Zona dell'evento («entro 12 km da Valdoria») per area e domanda di un bene.
public static string Where(ClientWorld w, WorldEventInfo e)
{
var def = Def(w, e);
string target = Target(w, e);
return def?.RadiusKm is { } km ? $"{T("entro")} {Fmt.Number(km, 0)} km {T("da")} {target}" : target;
}
///
/// Scadenza: ultimo giorno dell'evento (EndDay − 1) e giorni che restano, oggi compreso. Il server
/// toglie l'evento il mattino di EndDay, quindi il conto va dalla durata estratta a 1. Un evento
/// estratto oggi inizia domani: si dice da quando, con la sua durata.
///
public static string Until(ClientWorld w, WorldEventInfo e)
{
long today = Fmt.Today(w);
string until = $"{T("fino al")} {Fmt.Date(w, e.EndDay - 1)}";
if (e.StartDay > today)
{
string from = e.StartDay == today + 1 ? T("da domani") : $"{T("dal")} {Fmt.Date(w, e.StartDay)}";
return $"{from} {until} ({Days(e.EndDay - e.StartDay)})";
}
return $"{until} ({Days(Math.Max(1, e.EndDay - today))})";
}
private static string Days(long n) => $"{n} {(n == 1 ? T("giorno") : T("giorni"))}";
/// Colore della gravità: opportunità in verde, avvisi in ambra, critici in rosso.
public static Color Color(WorldEventInfo e) => e.Severity switch
{
1 => Palette.Ok,
2 => Palette.AmberLight,
3 => Palette.Danger,
_ => Palette.Text,
};
/// Riga compatta: titolo, luogo, effetti e scadenza.
public static Control Row(ClientWorld w, WorldEventInfo e)
{
var col = PanelKit.Column(2);
col.AddChild(UiTheme.Text($"{Name(w, e)} · {Where(w, e)}", 14, Color(e), bold: true));
var effects = UiTheme.Text(Effects(w, e), 12, Palette.Text);
effects.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(effects);
col.AddChild(UiTheme.Text(Until(w, e), 12, Palette.TextSecondary));
return col;
}
///
/// Eventi che riguardano un'entità: bersaglio diretto oppure, per una città, zona (maltempo,
/// domanda di un bene) che la contiene. Come sul server, una città è nella zona se dista dalla città
/// centro al più il raggio del catalogo.
///
public static IEnumerable For(ClientWorld w, byte entity, int index) =>
(w.LastDigest?.WorldEvents ?? []).Where(e => (e.Entity == entity && e.EntityIndex == index) || (entity == TownEntity && InZone(w, e, index)));
private static bool InZone(ClientWorld w, WorldEventInfo e, int town)
{
if (e.Entity != TownEntity || Def(w, e)?.RadiusKm is not { } km) return false;
if (!w.Towns.TryGetValue(town, out var t) || !w.Towns.TryGetValue(e.EntityIndex, out var center)) return false;
double r = km * 1000;
return (t.Position - center.Position).LengthSquared <= r * r;
}
/// Avvisi «Evento in corso» per la scheda dell'entità.
public static void AddNotices(ClientWorld w, Control into, byte entity, int index)
{
foreach (var e in For(w, entity, index))
into.AddChild(UiTheme.Notice($"{T("Evento in corso")}: {Name(w, e)} · {Effects(w, e)} · {Until(w, e)}"));
}
public const byte Town = TownEntity, Industry = IndustryEntity, Depot = DepotEntity;
}