using DinerContracts.BindingModels; using DinerContracts.ViewModels; using DinerDataModels.Models; using System.Xml.Linq; namespace DinerFileImplement.Models { public class Snack : ISnackModel { public int Id { get; private set; } public string SnackName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _snackComponents = null; public Dictionary SnackComponents { get { if (_snackComponents == null) { var source = DataFileSingleton.GetInstance(); _snackComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _snackComponents; } } public static Snack? Create(SnackBindingModel model) { if (model == null) { return null; } return new Snack() { Id = model.Id, SnackName = model.SnackName, Price = model.Price, Components = model.SnackComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Snack? Create(XElement element) { if (element == null) { return null; } return new Snack() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), SnackName = element.Element("SnackName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("SnackComponents")!.Elements("SnackComponent") .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(SnackBindingModel model) { if (model == null) { return; } SnackName = model.SnackName; Price = model.Price; Components = model.SnackComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _snackComponents = null; } public SnackViewModel GetViewModel => new() { Id = Id, SnackName = SnackName, Price = Price, SnackComponents = SnackComponents }; public XElement GetXElement => new("Snack", new XAttribute("Id", Id), new XElement("SnackName", SnackName), new XElement("Price", Price.ToString()), new XElement("SnackComponents", Components.Select(x => new XElement("SnackComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }