PIbd-23_Polevoy_S.V._Flower.../FlowerShop/FlowerShopFileImplement/Models/Bouquet.cs

105 lines
3.3 KiB
C#
Raw Normal View History

using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
using System.Linq;
namespace FlowerShopFileImplement.Models
{
public class Bouquet : IBouquetModel
{
public string BouquetName { get; private set; } = string.Empty;
public double Price { get; private set; }
public int Id { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _bouquetComponents = new();
public Dictionary<int, (IComponentModel, int)> BouquetComponents
{
get
{
if (_bouquetComponents == null)
{
var source = DataFileSingleton.GetInstance();
_bouquetComponents = Components.ToDictionary(
x => x.Key,
y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value)
);
}
return _bouquetComponents;
}
}
public static Bouquet? Create(BouquetBindingModel? model)
{
if (model == null)
{
return null;
}
return new Bouquet()
{
Id = model.Id,
BouquetName = model.BouquetName,
Price = model.Price,
Components = model.BouquetComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Bouquet? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Bouquet()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
BouquetName = element.Element("BouquetName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("BouquetComponents")!.Elements("BouquetComponent").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(BouquetBindingModel? model)
{
if (model == null)
{
return;
}
BouquetName = model.BouquetName;
Price = model.Price;
Components = model.BouquetComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_bouquetComponents = null;
}
public BouquetViewModel GetViewModel => new()
{
Id = Id,
BouquetName = BouquetName,
Price = Price,
BouquetComponents = BouquetComponents
};
public XElement GetXElement => new(
"Bouquet",
new XAttribute("Id", Id),
new XElement("BouquetName", BouquetName),
new XElement("Price", Price.ToString()),
new XElement("BouquetComponents", Components.Select(x =>
new XElement("BouquetComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray())
);
}
}