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"; private readonly string MessageInfoFileName = "MessageInfo.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Repairs { get; private set; } public List Clients { get; private set; } public List Implementers { get; private set; } public List Messages { 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)!)!; Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.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); public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", 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); } } } }