ISEbd_21_Kuklew_M.I._Softwa.../SoftwareInstallationFileImplement/Models/Package.cs
Максим Куклев 757c1ea0f0 загрузил
2024-05-12 14:45:39 +04:00

81 lines
3.1 KiB
C#

using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Models;
using System.Xml.Linq;
namespace SoftwareInstallationFileImplement.Models
{
public class Package : IPackageModel
{
public int Id { get; private set; }
public string PackageName { 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)>? _pizzaComponents = null;
public Dictionary<int, (IComponentModel, int)> PackageComponents
{
get
{
if (_pizzaComponents == null)
{
var source = DataFileSingleton.GetInstance();
_pizzaComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _pizzaComponents;
}
}
public static Package? Create(PackageBindingModel model)
{
if (model == null)
{
return null;
}
return new Package()
{
Id = model.Id,
PackageName = model.PackageName,
Price = model.Price,
Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Package? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Package()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
PackageName = element.Element("PackageName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("PackageComponents")!.Elements("PackageComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(PackageBindingModel model)
{
if (model == null)
{
return;
}
PackageName = model.PackageName;
Price = model.Price;
Components = model.PackageComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_pizzaComponents = null;
}
public PackageViewModel GetViewModel => new()
{
Id = Id,
PackageName = PackageName,
Price = Price,
PackageComponents = PackageComponents
};
public XElement GetXElement => new("Package",
new XAttribute("Id", Id),
new XElement("PackageName", PackageName),
new XElement("Price", Price.ToString()),
new XElement("PackageComponents", Components.Select(
x => new XElement("PackageComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}