using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ConfectioneryContracts.BindingModels; using ConfectioneryContracts.ViewModels; using ConfectioneryDataModels.Models; using System.Xml.Linq; namespace ConfectioneryFileImplement.Models { public class Pastry : IPastryModel { public int Id { get; private set; } public string PastryName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _pastryComponents = null; public Dictionary PastryComponents { get { if (_pastryComponents == null) { var source = DataFileSingleton.GetInstance(); _pastryComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _pastryComponents; } } public static Pastry? Create(PastryBindingModel model) { if (model == null) { return null; } return new Pastry() { Id = model.Id, PastryName = model.PastryName, Price = model.Price, Components = model.PastryComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Pastry? Create(XElement element) { if (element == null) { return null; } return new Pastry() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PastryName = element.Element("PastryName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("PastryComponents")!.Elements("PastryComponent") .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(PastryBindingModel model) { if (model == null) { return; } PastryName = model.PastryName; Price = model.Price; Components = model.PastryComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _pastryComponents = null; } public PastryViewModel GetViewModel => new() { Id = Id, PastryName = PastryName, Price = Price, PastryComponents = PastryComponents }; public XElement GetXElement => new("Pastry", new XAttribute("Id", Id), new XElement("PastryName", PastryName), new XElement("Price", Price.ToString()), new XElement("PastryComponents", Components.Select(x => new XElement("PastryComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }