using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.ViewModels; using SecuritySystemDataModels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SecuritySystemFileImplement.Models { //класс реализующий интерфейс модели изделия public class Secure : ISecureModel { public int Id { get; private set; } public string SecureName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Sensors { get; private set; } = new(); private Dictionary? _secureSensors = null; public Dictionary SecureSensors { get { if (_secureSensors == null) { var source = DataFileSingleton.GetInstance(); _secureSensors = Sensors.ToDictionary(x => x.Key, y => ((source.Sensors.FirstOrDefault(z => z.Id == y.Key) as ISensorModel)!, y.Value)); } return _secureSensors; } } public static Secure? Create(SecureBindingModel model) { if (model == null) { return null; } return new Secure() { Id = model.Id, SecureName = model.SecureName, Price = model.Price, Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2) }; } public static Secure? Create(XElement element) { if (element == null) { return null; } return new Secure() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), SecureName = element.Element("SecureName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Sensors = element.Element("SecureSensors")!.Elements("SecureSensors").ToDictionary( x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(SecureBindingModel model) { if (model == null) { return; } SecureName = model.SecureName; Price = model.Price; Sensors = model.SecureSensors.ToDictionary(x => x.Key, x => x.Value.Item2); _secureSensors = null; } public SecureViewModel GetViewModel => new() { Id = Id, SecureName = SecureName, Price = Price, SecureSensors = SecureSensors }; public XElement GetXElement => new("Secure", new XAttribute("Id", Id), new XElement("SecureName", SecureName), new XElement("Price", Price.ToString()), new XElement("SecureSensors", Sensors.Select( x => new XElement("SecureSensors", new XElement("Key", x.Key), new XElement("Value", x.Value)) ).ToArray())); } }