PIbd-22_Isaeva_A.I._FishFac.../FishFactoryFileImplement/Models/Canned.cs
2024-03-02 12:10:12 +04:00

89 lines
3.1 KiB
C#

using FishFactoryContracts.BindingModels;
using FishFactoryContracts.ViewModels;
using FishFactoryDataModel.Models;
using FishFactoryFileImplement;
using System.Xml.Linq;
namespace FishFactoryFileImplement.Models
{
internal class Canned : ICannedModel
{
public int Id { get; private set; }
public string CannedName { 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)>? _cannedComponents = null;
public Dictionary<int, (IComponentModel, int)> CannedComponents
{
get
{
if (_cannedComponents == null)
{
var source = DataFileSingleton.GetInstance();
_cannedComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _cannedComponents;
}
}
public static Canned? Create(CannedBindingModel? model)
{
if (model == null)
{
return null;
}
return new Canned()
{
Id = model.Id,
CannedName = model.CannedName,
Price = model.Price,
Components = model.CannedComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Canned? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Canned()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
CannedName = element.Element("CannedName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("CannedComponents")!.Elements("CannedComponent").ToDictionary
(x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))};
}
public void Update(CannedBindingModel? model)
{
if (model == null)
{
return;
}
CannedName = model.CannedName;
Price = model.Price;
Components = model.CannedComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_cannedComponents = null;
}
public CannedViewModel GetViewModel => new()
{
Id = Id,
CannedName = CannedName,
Price = Price,
CannedComponents = CannedComponents
};
public XElement GetXElement => new("Canned",
new XAttribute("Id", Id),
new XElement("CannedName", CannedName),
new XElement("Price", Price.ToString()),
new XElement("CannedComponents", Components.Select(x =>
new XElement("CannedComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}