PIbd-22_Shabunov_O.A._AutoW.../AutoWorkshopFileImplement/DataFileSingleton.cs
2024-04-16 19:50:39 +04:00

70 lines
2.8 KiB
C#

using AutoWorkshopFileImplement.Models;
using System.Xml.Linq;
namespace AutoWorkshopFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? _instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string RepairFileName = "Repair.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Repair> Repairs { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Repairs = LoadData(RepairFileName, "Repair", x => Repair.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
public static DataFileSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataFileSingleton();
}
return _instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveRepairs() => SaveData(Repairs, RepairFileName, "Repairs", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private static List<T>? LoadData<T>(string FileName, string XmlNodeName, Func<XElement, T> SelectFunction)
{
if (File.Exists(FileName))
{
return XDocument.Load(FileName)?.Root?.Elements(XmlNodeName)?.Select(SelectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> Data, string FileName, string XmlNodeName, Func<T, XElement> SelectFunction)
{
if (Data != null)
{
new XDocument(new XElement(XmlNodeName, Data.Select(SelectFunction).ToArray())).Save(FileName);
}
}
}
}