PIbd22_Kuznetsov_A.V._Sewin.../SewingDresses/SewingDressesFileImplement/Models/Dress.cs

79 lines
3.0 KiB
C#
Raw Permalink Normal View History

2024-05-04 19:42:41 +04:00
using SewingDressesContracts.BindingModels;
using SewingDressesContracts.ViewModels;
using SewingDressesDataModels.Models;
using System.Xml.Linq;
namespace SewingDressesFileImplement.Models
{
public class Dress : IDressModel
{
public int Id { get; private set; }
public string DressName { 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)>? _dressComponents = null;
public Dictionary<int, (IComponentModel, int)> DressComponents
{
get
{
if (_dressComponents == null)
{
var source = DataFileSingleton.GetInstance();
_dressComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _dressComponents;
}
}
public static Dress? Create(DressBindingModel model)
{
if (model == null)
{
return null;
}
return new Dress()
{
Id = model.Id,
DressName = model.DressName,
Price = model.Price,
Components = model.DressComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Dress? Create(XElement element)
{
if (element == null)
{ return null; }
return new Dress()
{
Id = Convert.ToInt32(element.Attribute("Id")?.Value),
DressName = element.Element("DressName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value, new System.Globalization.CultureInfo("en-US")),
Components = element.Element("DressComponents")!.Elements("DressComponent").ToDictionary(x =>Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(DressBindingModel model)
{
if (model == null)
{
return;
}
DressName = model.DressName;
Price = model.Price;
Components = model.DressComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_dressComponents = null;
}
public DressViewModel GetViewModel => new()
{
Id = Id,
DressName = DressName,
Price = Price,
DressComponents = DressComponents
};
public XElement GetXElement => new("Dress",
new XAttribute("Id", Id),
new XElement("DressName", DressName),
new XElement("Price", Price),
new XElement("DressComponents", Components.Select(x => new XElement("DressComponent", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}