using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Screens;
using RailEnterprise.Core.Data;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client;
///
/// Nodo radice: tema e traduzioni, dati del gioco, passaggio tra schermata di connessione e partita;
/// alla chiusura termina la sessione e l'eventuale server locale.
///
public partial class Main : Node
{
private const string SettingsPath = "user://settings.cfg";
private GameData? _data;
private Node? _screen;
private GameSession? _session;
private string? _autopilot;
public override void _Ready()
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
string locale = (string)cfg.GetValue("ui", "locale", "it");
Localization.Load(locale);
GetWindow().Theme = UiTheme.Build();
GetWindow().Title = "Rail Enterprise";
try
{
_data = GodotDataSource.LoadGameData();
}
catch (Exception e)
{
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
}
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
var args = OS.GetCmdlineUserArgs();
int i = Array.IndexOf(args, "--autopilot");
if (i >= 0 && _data is not null)
{
// collaudo: mappa piccola e seme fisso per il server locale
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
StartLocal();
}
}
private void Swap(Node screen)
{
_screen?.QueueFree();
_screen = screen;
AddChild(screen);
}
/// Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.
private void ShowMenu(string status = "")
{
if (_data is null)
{
// senza dati non si può aprire nessuna sessione: resta solo il messaggio
var label = UiTheme.Text(status, 16, Palette.Danger);
label.SetAnchorsAndOffsetsPreset(Control.LayoutPreset.Center);
Swap(label);
return;
}
var screen = new ConnectScreen(_data);
screen.PlayRequested += ShowGame;
screen.LanguageChanged += code =>
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("ui", "locale", code);
cfg.Save(SettingsPath);
TranslationServer.SetLocale(code);
ShowMenu();
};
Swap(screen);
if (status.Length > 0) screen.SetStatus(status, error: true);
}
/// Collaudo: server locale da zero e subito in partita, senza la schermata di connessione.
private async void StartLocal()
{
if (_data is null) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
return;
}
var launcher = new LocalServerLauncher();
try
{
string dataDir = ProjectSettings.GlobalizePath("user://autopilot-server");
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
int port = await launcher.StartAsync(server, dataDir, TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
ShowGame(session);
}
catch (Exception e)
{
launcher.Dispose();
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
}
}
private void ShowGame(GameSession session)
{
_session = session;
var game = new GameScreen(session);
game.Exit += async () =>
{
var s = _session;
_session = null;
ShowMenu();
if (s is not null) await s.DisposeAsync();
};
Swap(game);
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
}
public override void _Notification(int what)
{
if (what != NotificationWMCloseRequest) return;
// anche la sessione di prova della schermata di connessione chiude il suo server locale
var session = _session ?? (_screen as ConnectScreen)?.TakeSession();
_session = null;
session?.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(3));
}
}