PIbd-22_Safiulova_K.N._Airc.../AircraftPlant/AircraftPlantFileImplement/Plane.cs

92 lines
3.2 KiB
C#
Raw Normal View History

2024-03-13 00:15:40 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDataModels.Models;
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<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _planeComponents =
null;
public Dictionary<int, (IComponentModel, int)> 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()));
}
}