using TypographyDataModels.Models; using TypographyContracts.BindingModels; using TypographyContracts.ViewModels; using System.Xml.Linq; namespace TypographyFileImplement.Models { public class Printed : IPrintedModel { public int Id { get; private set; } public string PrintedName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _srintedComponents = null; public Dictionary PrintedComponents { get { if (_srintedComponents == null) { var source = DataFileSingleton.GetInstance(); _srintedComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _srintedComponents; } } public static Printed? Create(PrintedBindingModel model) { if (model == null) { return null; } return new Printed() { Id = model.Id, PrintedName = model.PrintedName, Price = model.Price, Components = model.PrintedComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Printed? Create(XElement element) { if (element == null) { return null; } return new Printed() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PrintedName = element.Element("PrintedName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("PrintedComponents")!.Elements("PrintedComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(PrintedBindingModel model) { if (model == null) { return; } PrintedName = model.PrintedName; Price = model.Price; Components = model.PrintedComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _srintedComponents = null; } public PrintedViewModel GetViewModel => new() { Id = Id, PrintedName = PrintedName, Price = Price, PrintedComponents = PrintedComponents }; public XElement GetXElement => new("Printed", new XAttribute("Id", Id), new XElement("PrintedName", PrintedName), new XElement("Price", Price.ToString()), new XElement("PrintedComponents", Components.Select(x => new XElement("PrintedComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }