using System.Text.Json;
using System.Text.Json.Serialization;
using Server.Model;
namespace Server.Data
{
public class CustomerData
{
#region Public Properties
public List
Customers { get; set; } = [];
public static CustomerData Instance { get; set; } = new();
#endregion
///
/// Retrieves the file path for the settings JSON file.
///
/// The file path of the settings JSON file as a string.
private static string GetFilePath()
{
var parentDirectory = Directory.GetParent(Directory.GetCurrentDirectory());
if (parentDirectory == null) return "Customers.json";
return Path.Combine(parentDirectory.FullName, "Customers.json");
}
#region Public Method LoadAsync
///
/// Loads customer data asynchronously from a JSON file if it exists.
///
///
/// A Task representing the asynchronous operation.
///
public static async Task LoadAsync()
{
if (!File.Exists(GetFilePath())) return;
var jsonString = await File.ReadAllTextAsync(GetFilePath());
var deserialized = JsonSerializer.Deserialize(jsonString)!;
Instance = deserialized;
}
#endregion
#region Public Method SaveAsync
///
/// Saves the current customer data asynchronously to a JSON file.
///
///
/// A Task representing the asynchronous operation.
///
public static async Task SaveAsync()
{
var jsonString = JsonSerializer.Serialize(Instance, new JsonSerializerOptions { WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
await File.WriteAllTextAsync(GetFilePath(), jsonString);
}
#endregion
}
}