using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace AircraftPlantFileImplement.Models { /// /// Сущность "Изделие" /// public class Plane : IPlaneModel { /// /// Идентификатор /// public int Id { get; private set; } /// /// Название изделия /// public string PlaneName { get; private set; } = string.Empty; /// /// Стоимость изделия /// public double Price { get; private set; } /// /// Коллекция компонентов изделия в виде /// «идентификатор компонента – количество компонентов» /// public Dictionary Components { get; private set; } = new(); /// /// Коллекция компонентов изделия /// private Dictionary? _planeComponents = null; public Dictionary PlaneComponents { get { if (_planeComponents == null) { var source = DataFileSingleton.GetInstance(); _planeComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)); } return _planeComponents; } } /// /// Создание модели изделия /// /// /// public static Plane? Create(PlaneBindingModel? model) { if (model == null) { return null; } return new Plane() { Id = model.Id, PlaneName = model.PlaneName, Price = model.Price, Components = model.PlaneComponents.ToDictionary(x => x.Key, x => x.Value.Item2) }; } /// /// Создание модели изделия из данных файла /// /// /// public static Plane? Create(XElement element) { if (element == null) { return null; } return new Plane() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), PlaneName = element.Element("PlaneName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Components = element.Element("PlaneComponents")!.Elements("PlaneComponent") .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) }; } /// /// Изменение модели изделия /// /// public void Update(PlaneBindingModel? model) { if (model == null) { return; } PlaneName = model.PlaneName; Price = model.Price; Components = model.PlaneComponents.ToDictionary(x => x.Key, x => x.Value.Item2); _planeComponents = null; } /// /// Получение модели изделия /// public PlaneViewModel GetViewModel => new() { Id = Id, PlaneName = PlaneName, Price = Price, PlaneComponents = PlaneComponents }; /// /// Запись данных о модели изделия в файл /// public XElement GetXElement => new("Plane", new XAttribute("Id", Id), new XElement("PlaneName", PlaneName), new XElement("Price", Price.ToString()), new XElement("PlaneComponents", Components.Select(x => new XElement("PlaneComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }