using IceCreamShopContracts.BindingModels; using IceCreamShopContracts.ViewModels; using IceCreamShopDataModels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace IceCreamShopFileImplement.Models { public class IceCream : IIceCreamModel { public int Id { get; private set; } public string IceCreamName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _iceCreamComponents = null; public Dictionary IceCreamComponents { get { if (_iceCreamComponents == null) { var source = DataFileSingleton.GetInstance(); _iceCreamComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _iceCreamComponents; } } public static IceCream? Create(IceCreamBindingModel model) { if (model == null) { return null; } return new IceCream() { Id = model.Id, IceCreamName = model.IceCreamName, Price = model.Price, Components = model.IceCreamComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static IceCream? Create(XElement element) { if (element == null) { return null; } return new IceCream() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), IceCreamName = element.Element("IceCreamName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("IceCreamComponents")!.Elements("IceCreamComponent") .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(IceCreamBindingModel model) { if (model == null) { return; } IceCreamName = model.IceCreamName; Price = model.Price; Components = model.IceCreamComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _iceCreamComponents = null; } public IceCreamViewModel GetViewModel => new() { Id = Id, IceCreamName = IceCreamName, Price = Price, IceCreamComponents = IceCreamComponents }; public XElement GetXElement => new("IceCream", new XAttribute("Id", Id), new XElement("IceCreamName", IceCreamName), new XElement("Price", Price.ToString()), new XElement("IceCreamComponents", Components.Select(x => new XElement("IceCreamComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }