92 lines
3.0 KiB
C#
92 lines
3.0 KiB
C#
using System.Reflection.PortableExecutable;
|
|
using Splat;
|
|
|
|
namespace StarsAssistant.Services;
|
|
|
|
public class Game
|
|
{
|
|
/// <summary>
|
|
/// Default constructor, initialize required fields manually, targeted
|
|
/// for Initial DB creation.
|
|
/// </summary>
|
|
public Game() {}
|
|
|
|
/// <summary>
|
|
/// Init game state from database, targeted for CLI arg.
|
|
/// </summary>
|
|
/// <param name="dbGame">Record loaded from DB</param>
|
|
public Game(Model.Game dbGame)
|
|
{
|
|
GamePath = dbGame.GamePath;
|
|
BaseName = dbGame.BaseName;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
/// <param name="db">Optional DB instance if services are yet unavailable.</param>
|
|
public void SaveToDatabase(Model.StarsDatabase? db = null)
|
|
{
|
|
db ??= Locator.Current.GetService<Model.StarsDatabase>()!;
|
|
|
|
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();
|
|
}
|
|
|
|
/// <summary>
|
|
/// The base path in which all game files reside.
|
|
/// </summary>
|
|
public string GamePath { get; set; } = String.Empty;
|
|
|
|
/// <summary>
|
|
/// The base name without extensions of your game, inside the GamePath folder.
|
|
/// All dependant files are resolved using this name.
|
|
/// </summary>
|
|
public string BaseName { get; set; } = String.Empty;
|
|
|
|
/// <summary>
|
|
/// Combine into the DatabaseName
|
|
/// </summary>
|
|
public string DatabaseFileName => Path.Combine(GamePath, $"{BaseName}.sqlite");
|
|
|
|
/// <summary>
|
|
/// Search for Planet files using this pattern, will give you all pxx files.
|
|
/// </summary>
|
|
public string PlanetFileSearchPattern => $"{BaseName}.p*";
|
|
|
|
/// <summary>
|
|
/// Internal helper to lazily load the current player from the DB.
|
|
/// </summary>
|
|
private readonly static Lazy<Model.Race>LazyPlayer = new ( () => {
|
|
using var db = Locator.Current.GetService<Model.StarsDatabase>()!;
|
|
Model.Race result = db.Race
|
|
.Where(r => r.PlayerRace == true)
|
|
.First();
|
|
return result;
|
|
});
|
|
|
|
/// <summary>
|
|
/// Get the Race object for the current player, lazy initialized.
|
|
/// </summary>
|
|
public static Model.Race Player => LazyPlayer.Value;
|
|
|
|
/// <summary>
|
|
/// Get the name of a planet file for a given race.
|
|
/// </summary>
|
|
/// <param name="r">The race to load.</param>
|
|
/// <returns>Fully qualified file path.</returns>
|
|
public string PlanetFileForRace (Model.Race r) => Path.Combine(GamePath, $"{BaseName}.p{r.PlayerFileId}");
|
|
|
|
}
|