PIbd21_Makarov_DV_FlowerShop/FlowerShop/FlowerShopFileImplement/Models/Flower.cs

92 lines
3.1 KiB
C#
Raw Normal View History

2024-03-08 23:06:46 +04:00
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Flower : IFlowerModel
{
public int Id { get; private set; }
public string FlowerName { 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)>? _flowerComponents = null;
public Dictionary<int, (IComponentModel, int)> FlowerComponents
{
get
{
if (_flowerComponents == null)
{
var source = DataFileSingleton.GetInstance();
_flowerComponents = Components.ToDictionary(x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _flowerComponents;
}
}
public static Flower? Create(FlowerBindingModel model)
{
if (model == null)
{
return null;
}
return new Flower()
{
Id = model.Id,
FlowerName = model.FlowerName,
Price = model.Price,
Components = model.FlowerComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Flower? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Flower()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
FlowerName = element.Element("FlowerName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("FlowerComponents")!.Elements("FlowerComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(FlowerBindingModel model)
{
if (model == null)
{
return;
}
FlowerName = model.FlowerName;
Price = model.Price;
Components = model.FlowerComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_flowerComponents = null;
}
public FlowerViewModel GetViewModel => new()
{
Id = Id,
FlowerName = FlowerName,
Price = Price,
FlowerComponents = FlowerComponents
};
public XElement GetXElement => new("Flower",
new XAttribute("Id", Id),
new XElement("FlowerName", FlowerName),
new XElement("Price", Price.ToString()),
new XElement("FlowerComponents", Components.Select(x =>
new XElement("FlowerComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}