using BarContracts.BindingModels; using BarContracts.ViewModels; using BarDataModels.Models; using System.Collections.Generic; using System.Xml.Linq; namespace BarFileImplement.Models { public class Cocktail : ICocktailModel { public int Id { get; private set; } public string CocktailName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _cocktailComponents = null; public Dictionary CocktailComponents { get { if (_cocktailComponents == null) { var source = DataFileSingleton.GetInstance(); _cocktailComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _cocktailComponents; } } public static Cocktail? Create(CocktailBindingModel model) { if (model == null) { return null; } return new Cocktail() { Id = model.Id, CocktailName = model.CocktailName, Price = model.Price, Components = model.CocktailComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Cocktail? Create(XElement element) { if (element == null) { return null; } return new Cocktail() { Id = Convert.ToInt32(element.Attribute("Id")?.Value), CocktailName = element.Element("CocktailName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value, new System.Globalization.CultureInfo("en-US")), Components = element.Element("CocktailComponents")!.Elements("CocktailComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(CocktailBindingModel model) { if (model == null) { return; } CocktailName = model.CocktailName; Price = model.Price; Components = model.CocktailComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _cocktailComponents = null; } public CocktailViewModel GetViewModel => new() { Id = Id, CocktailName = CocktailName, Price = Price, CocktailComponents = CocktailComponents }; public XElement GetXElement => new("Cocktail", new XAttribute("Id", Id), new XElement("CocktailName", CocktailName), new XElement("Price", Price), new XElement("CocktailComponents", Components.Select(x => new XElement("CocktailComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }