using FurnitureAssemblyContracts.BindingModels; using FurnitureAssemblyContracts.ViewModels; using FurnitureAssemblyDataModels.Models; using System.Runtime.Serialization; using System.Xml.Linq; namespace FurnitureAssemblyFileImplement.Models { [DataContract] public class Furniture : IFurnitureModel { [DataMember] public int Id { get; private set; } [DataMember] public string FurnitureName { get; private set; } = string.Empty; [DataMember] public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _furnitureComponents = null; [DataMember] public Dictionary FurnitureComponents { get { if (_furnitureComponents == null) { var source = DataFileSingleton.GetInstance(); _furnitureComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _furnitureComponents; } } public static Furniture? Create(FurnitureBindingModel model) { if (model == null) { return null; } return new Furniture() { Id = model.Id, FurnitureName = model.FurnitureName, Price = model.Price, Components = model.FurnitureComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Furniture? Create(XElement element) { if (element == null) { return null; } return new Furniture() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), FurnitureName = element.Element("FurnitureName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("FurnitureComponents")!.Elements("FurnitureComponent").ToDictionary( x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(FurnitureBindingModel model) { if (model == null) { return; } FurnitureName = model.FurnitureName; Price = model.Price; Components = model.FurnitureComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _furnitureComponents = null; } public FurnitureViewModel GetViewModel => new() { Id = Id, FurnitureName = FurnitureName, Price = Price, FurnitureComponents = FurnitureComponents }; public XElement GetXElement => new("Furniture", new XAttribute("Id", Id), new XElement("FurnitureName", FurnitureName), new XElement("Price", Price.ToString()), new XElement("FurnitureComponents", Components.Select( x => new XElement("FurnitureComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }