using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels; using ConfectioneryDataModels.Models; using System.Xml.Linq; namespace ConfectioneryFileImplement { public class Shop : IShopModel { public string Name { get; private set; } = string.Empty; public string Address { get; private set; } = string.Empty; public DateTime DateOpening { get; private set; } public Dictionary CountPastries { get; private set; } = new(); private Dictionary? _cachedPastries = null; public Dictionary Pastries { get { if (_cachedPastries == null) { var source = DataFileSingleton.GetInstance(); _cachedPastries = CountPastries .ToDictionary(x => x.Key, x => (source.Pastries .FirstOrDefault(y => y.Id == x.Key)! as IPastryModel, x.Value)); } return _cachedPastries; } } public int Id { get; private set; } public static Shop? Create(ShopBindingModel? model) { if (model == null) { return null; } return new Shop() { Id = model.Id, Name = model.Name, Address = model.Address, DateOpening = model.DateOpening, CountPastries = new() }; } public static Shop? Create(XElement element) { if (element == null) { return null; } return new() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), Name = element.Element("Name")!.Value, Address = element.Element("Address")!.Value, DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), CountPastries = element.Element("CountPastries")!.Elements("CountPastry") .ToDictionary( x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value) ) }; } public void Update(ShopBindingModel? model) { if (model == null) { return; } Name = model.Name; Address = model.Address; DateOpening = model.DateOpening; CountPastries = model.Pastries.ToDictionary(x => x.Key, x => x.Value.Item2); _cachedPastries = null; } public ShopViewModel GetViewModel => new() { Id = Id, Name = Name, Address = Address, Pastries = Pastries, DateOpening = DateOpening, }; public XElement GetXElement => new("Order", new XAttribute("Id", Id), new XElement("Name", Name), new XElement("Address", Address), new XElement("DateOpening", DateOpening), new XElement("CountPastries", CountPastries .Select(x => new XElement("CountPastry", new XElement("Key", x.Key), new XElement("Value", x.Value)) )) ); } }