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"; public List Components { get; private set; } public List Orders { get; private set; } public List Repairs { 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)!)!; } 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); private static List? LoadData(string FileName, string XmlNodeName, Func SelectFunction) { if (File.Exists(FileName)) { return XDocument.Load(FileName)?.Root?.Elements(XmlNodeName)?.Select(SelectFunction)?.ToList(); } return new List(); } private static void SaveData(List Data, string FileName, string XmlNodeName, Func SelectFunction) { if (Data != null) { new XDocument(new XElement(XmlNodeName, Data.Select(SelectFunction).ToArray())).Save(FileName); } } } }