using RailEnterprise.Core.Common;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Rail;
using RailEnterprise.Core.Time;
namespace RailEnterprise.Core.Simulation;
///
/// Evento del mondo in corso (ADR 0017): tipo del catalogo, bersaglio, bene (per la domanda di un
/// bene), giorno d'inizio e di fine e intensità in [0, 1] da cui si ricavano i moltiplicatori.
///
public sealed class ActiveWorldEvent
{
public required int Id { get; init; }
public required WorldEventDef Def { get; init; }
/// Entità bersaglio: industria, città (anche centro di zona e area) o deposito.
public required EntityKind TargetKind { get; init; }
public required int Target { get; init; }
/// Bene coinvolto (TownGood), altrimenti −1.
public int Good { get; init; } = -1;
public required long StartDay { get; init; }
/// Primo giorno senza l'evento: dura EndDay − StartDay giorni.
public required long EndDay { get; init; }
public required double Intensity { get; init; }
/// Centro della zona in metri (città bersaglio), per area e domanda di un bene.
public Vec2 Center { get; init; }
/// Quadrato del raggio della zona in metri (0 senza zona).
public double RadiusSquaredM { get; init; }
public int DurationDays => (int)(EndDay - StartDay);
/// Vero se l'evento è in vigore nel giorno indicato: [StartDay, EndDay).
public bool InForce(long day) => StartDay <= day && day < EndDay;
/// Moltiplicatore dell'effetto indicato (1 se il tipo non ce l'ha).
public double Effect(EventEffectKind kind)
{
foreach (var e in Def.Effects)
{
if (e.Kind == kind) return e.At(Intensity);
}
return 1.0;
}
public bool Has(EventEffectKind kind)
{
foreach (var e in Def.Effects)
{
if (e.Kind == kind) return true;
}
return false;
}
/// Moltiplicatore dell'effetto principale (il primo del catalogo).
public double Primary => Def.Effects[0].At(Intensity);
public bool InZone(Vec2 p) => RadiusSquaredM > 0 && (p - Center).LengthSquared <= RadiusSquaredM;
}
///
/// Eventi del mondo in corso: unica sorgente dei moltiplicatori temporanei letti dai sistemi. Ogni
/// interrogazione restituisce il prodotto degli effetti attivi sull'entità (1 senza eventi), così a
/// evento scaduto tutto torna come prima. L'elenco è in ordine d'inizio (id crescente) e contiene
/// gli eventi dall'estrazione fino al mattino del primo giorno libero: le interrogazioni contano solo
/// quelli in vigore nel giorno dell'orologio (), così un evento
/// estratto oggi agisce da domani anche sui treni e l'ultimo giorno agisce per intero (ADR 0017 §5).
///
public sealed class WorldEventState(GameClock clock)
{
private readonly List _active = [];
private int _areaEvents;
private long Today => clock.Day;
public IReadOnlyList Active => _active;
/// Prossimo id libero (mai riutilizzato).
public int NextId { get; set; }
internal void Add(ActiveWorldEvent e)
{
_active.Add(e);
Recount();
}
internal void RemoveAt(int index)
{
_active.RemoveAt(index);
Recount();
}
internal void Clear()
{
_active.Clear();
Recount();
}
private void Recount()
{
_areaEvents = 0;
foreach (var e in _active)
{
if (e.Def.Target == EventTarget.Area) _areaEvents++;
}
}
/// Vero se un evento dello stesso tipo è già in corso sullo stesso bersaglio.
public bool IsActive(WorldEventDef def, EntityKind kind, int target)
{
foreach (var e in _active)
{
if (e.Def == def && e.TargetKind == kind && e.Target == target) return true;
}
return false;
}
/// Vero se un evento in elenco (anche non ancora iniziato) ha l'effetto indicato.
public bool AnyWith(EventEffectKind kind)
{
foreach (var e in _active)
{
if (e.Has(kind)) return true;
}
return false;
}
/// Eventi il cui bersaglio diretto è l'entità (anche non ancora iniziati).
public IEnumerable For(EntityKind kind, int index)
{
foreach (var e in _active)
{
if (e.TargetKind == kind && e.Target == index) yield return e;
}
}
/// Capacità produttiva dell'industria (IndustrySystem, DemandSystem).
public double IndustryCapacity(IndustryId industry)
{
double f = 1.0;
long day = Today;
foreach (var e in _active)
{
if (e.TargetKind == EntityKind.Industry && e.Target == industry.Value && e.InForce(day)) f *= e.Effect(EventEffectKind.IndustryCapacity);
}
return f;
}
/// Domanda della città per un bene: eventi sulla città e sul bene nella zona.
public double TownDemand(Town town, int good)
{
if (_active.Count == 0) return 1.0;
double f = 1.0;
long day = Today;
foreach (var e in _active)
{
if (!e.InForce(day)) continue;
switch (e.Def.Target)
{
case EventTarget.Town when e.Target == town.Id.Value:
f *= e.Effect(EventEffectKind.TownDemand);
break;
case EventTarget.TownGood when e.Good == good && (e.Target == town.Id.Value || e.InZone(town.Position)):
f *= e.Effect(EventEffectKind.GoodDemand);
break;
}
}
return f;
}
///
/// Quota dei pendolari che si presenta al lavoro: eventi sulla città di provenienza (epidemia,
/// sciopero) e sul deposito di destinazione (sciopero del personale).
///
public double Attendance(TownId town, WorkplaceRef workplace)
{
if (_active.Count == 0) return 1.0;
double f = 1.0;
long day = Today;
foreach (var e in _active)
{
if (!e.InForce(day)) continue;
bool hit = e.Def.Target switch
{
EventTarget.Town => e.Target == town.Value,
EventTarget.Depot => workplace.Kind == WorkplaceKind.Depot && e.Target == workplace.Index,
_ => false,
};
if (hit) f *= e.Effect(EventEffectKind.Attendance);
}
return f;
}
/// Velocità dei treni sull'arco (TrainSystem, a ogni tick): aree di maltempo in vigore oggi che contengono il suo punto medio.
public double EdgeSpeed(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrainSpeed, Today);
///
/// Usura del binario dovuta al traffico sull'arco (ConstructionSystem): il sistema la applica al
/// mattino al traffico del giorno prima, quindi conta il maltempo in vigore ieri.
///
public double EdgeWear(TrackEdge edge) => _areaEvents == 0 ? 1.0 : AreaEffect(edge, EventEffectKind.TrackWear, Today - 1);
private double AreaEffect(TrackEdge edge, EventEffectKind kind, long day)
{
int mid = edge.X.Length / 2;
var p = new Vec2(edge.X[mid], edge.Y[mid]);
double f = 1.0;
foreach (var e in _active)
{
if (e.Def.Target == EventTarget.Area && e.InForce(day) && e.InZone(p)) f *= e.Effect(kind);
}
return f;
}
}