using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.ViewModels; using PlumbingRepairDataModels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace PlumbingRepairFileImplement.Models { [DataContract] public class Work : IWorkModel { [DataMember] public int Id { get; private set; } [DataMember] public string WorkName { get; private set; } = string.Empty; [DataMember] public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); private Dictionary? _workComponents = null; [DataMember] public Dictionary WorkComponents { get { if(_workComponents == null) { var source = DataFileSingleton.GetInstance(); _workComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _workComponents; } } public static Work? Create(WorkBindingModel? model) { if (model == null) { return null; } return new Work() { Id = model.Id, WorkName = model.WorkName, Price = model.Price, Components = model.WorkComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Work? Create(XElement element) { if (element == null) { return null; } return new Work() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), WorkName = element.Element("WorkName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("WorkComponents")!.Elements("WorkComponent") .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(WorkBindingModel? model) { if (model == null) { return; } WorkName = model.WorkName; Price = model.Price; Components = model.WorkComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _workComponents = null; } public WorkViewModel GetViewModel => new() { Id = Id, WorkName = WorkName, Price = Price, WorkComponents = WorkComponents }; public XElement GetXElement => new("Work", new XAttribute("Id", Id), new XElement("WorkName", WorkName), new XElement("Price", Price.ToString()), new XElement("WorkComponents", Components.Select(x => new XElement("WorkComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }