using System.Reflection.PortableExecutable;
using Splat;
namespace StarsAssistant.Services;
public class Game
{
///
/// Default constructor, initialize required fields manually, targeted
/// for Initial DB creation.
///
public Game() {}
///
/// Init game state from database, targeted for CLI arg.
///
/// Record loaded from DB
public Game(Model.Game dbGame)
{
GamePath = dbGame.GamePath;
BaseName = dbGame.BaseName;
}
///
/// Save this record in the database. Uses the service locator to access the
/// database unless you specify an instance. This is needed during initial
/// game creation, where the services are not yet established.
///
/// Optional DB instance if services are yet unavailable.
public void SaveToDatabase(Model.StarsDatabase? db = null)
{
db ??= Locator.Current.GetService()!;
Model.Game? dbGame = db.Game.FirstOrDefault();
if (dbGame == null)
{
dbGame = new Model.Game();
db.Add(dbGame);
db.SaveChanges();
}
dbGame.GamePath = GamePath;
dbGame.BaseName = BaseName;
db.Update(dbGame);
db.SaveChanges();
}
///
/// The base path in which all game files reside.
///
public string GamePath { get; set; } = String.Empty;
///
/// The base name without extensions of your game, inside the GamePath folder.
/// All dependant files are resolved using this name.
///
public string BaseName { get; set; } = String.Empty;
///
/// Combine into the DatabaseName
///
public string DatabaseFileName => Path.Combine(GamePath, $"{BaseName}.sqlite");
///
/// Search for Planet files using this pattern, will give you all pxx files.
///
public string PlanetFileSearchPattern => $"{BaseName}.p*";
///
/// Internal helper to lazily load the current player from the DB.
///
private readonly static LazyLazyPlayer = new ( () => {
using var db = Locator.Current.GetService()!;
Model.Race result = db.Race
.Where(r => r.PlayerRace == true)
.First();
return result;
});
///
/// Get the Race object for the current player, lazy initialized.
///
public static Model.Race Player => LazyPlayer.Value;
///
/// Get the name of a planet file for a given race.
///
/// The race to load.
/// Fully qualified file path.
public string PlanetFileForRace (Model.Race r) => Path.Combine(GamePath, $"{BaseName}.p{r.PlayerFileId}");
}