using SoftwareInstallationContracts.BindingModels; using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationDataModels.Models; using System.Xml.Linq; namespace SoftwareInstallationFileImplement.Models { public class Package : IPackageModel { public int Id { get; private set; } public string PackageName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _pizzaComponents = null; public Dictionary PackageComponents { get { if (_pizzaComponents == null) { var source = DataFileSingleton.GetInstance(); _pizzaComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _pizzaComponents; } } public static Package? Create(PackageBindingModel model) { if (model == null) { return null; } return new Package() { Id = model.Id, PackageName = model.PackageName, Price = model.Price, Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Package? Create(XElement element) { if (element == null) { return null; } return new Package() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PackageName = element.Element("PackageName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("PackageComponents")!.Elements("PackageComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(PackageBindingModel model) { if (model == null) { return; } PackageName = model.PackageName; Price = model.Price; Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _pizzaComponents = null; } public PackageViewModel GetViewModel => new() { Id = Id, PackageName = PackageName, Price = Price, PackageComponents = PackageComponents }; public XElement GetXElement => new("Package", new XAttribute("Id", Id), new XElement("PackageName", PackageName), new XElement("Price", Price.ToString()), new XElement("PackageComponents", Components.Select( x => new XElement("PackageComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }