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

95 lines
3.4 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)>? _iceCreamComponents = null;
public Dictionary<int, (IComponentModel, int)> PackageComponents
{
get
{
if (_iceCreamComponents == null)
{
var source = DataFileSingleton.GetInstance();
_iceCreamComponents = Components.ToDictionary(x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _iceCreamComponents;
}
}
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);
_iceCreamComponents = 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()));
}
}