using BarFileImplement.Models;
using System.Xml.Linq;

namespace BarFileImplement
{
    public class DataFileSingleton
    {
        private static DataFileSingleton? _instance;

        private readonly string ComponentFileName = "Component.xml";
        private readonly string OrderFileName = "Order.xml";
        private readonly string CocktailFileName = "Cocktail.xml";
        private readonly string ClientFileName = "Client.xml";

        public List<Component> Components { get; private set; }

        public List<Order> Orders { get; private set; }

        public List<Cocktail> Cocktails { get; private set; }

        public List<Client> Clients { get; private set; }

        private DataFileSingleton()
        {
            Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
            Cocktails = LoadData(CocktailFileName, "Cocktail", x => Cocktail.Create(x)!)!;
            Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
            Clients = LoadData(ClientFileName, "Client", x => Client.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 SaveCocktails() => SaveData(Cocktails, CocktailFileName, "Cocktails", x => x.GetXElement);
        public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);

        public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", 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);
            }
        }
    }
}
