using AbstractShopFileImplement.Models;
using System.Xml.Linq;

namespace AbstractShopFileImplement
{
    internal class DataFileSingleton
    {
        private static DataFileSingleton? instance;

        private readonly string ComponentFileName = "Component.xml";

        private readonly string OrderFileName = "Order.xml";

        private readonly string ProductFileName = "Product.xml";

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

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

        public List<Product> Products { get; private set; }

        public static DataFileSingleton GetInstance()
        {
            if (instance == null)
            {
                instance = new DataFileSingleton();
            }
            return instance;
        }

        public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);

        public void SaveProducts() => SaveData(Products, ProductFileName, "Products", x => x.GetXElement);

        public void SaveOrders() { }

        private DataFileSingleton()
        {
            Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
            Products = LoadData(ProductFileName, "Product", x => Product.Create(x)!)!;
            Orders = new List<Order>();
        }

        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);
            }
        }
    }
}