PIbd-23-Salin-O.A.-IceCream.../IceCreamShop/IceCreamShopFileImplement/Models/IceCream.cs

106 lines
3.4 KiB
C#
Raw Normal View History

2024-02-18 14:16:34 +04:00
using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.ViewModels;
using IceCreamShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace IceCreamShopFileImplement.Models
{
public class IceCream : IIceCreamModel
{
public int Id { get; private set; }
public string IceCreamName { 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)> IceCreamComponents
{
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 IceCream? Create(IceCreamBindingModel model)
{
if (model == null)
{
return null;
}
return new IceCream()
{
Id = model.Id,
IceCreamName = model.IceCreamName,
Price = model.Price,
Components = model.IceCreamComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static IceCream? Create(XElement element)
{
if (element == null)
{
return null;
}
return new IceCream()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
IceCreamName = element.Element("IceCreamName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
2024-02-24 15:53:08 +04:00
element.Element("IceCreamComponents")!.Elements("IceCreamComponent")
2024-02-18 14:16:34 +04:00
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(IceCreamBindingModel model)
{
if (model == null)
{
return;
}
IceCreamName = model.IceCreamName;
Price = model.Price;
Components = model.IceCreamComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_iceCreamComponents = null;
}
public IceCreamViewModel GetViewModel => new()
{
Id = Id,
IceCreamName = IceCreamName,
Price = Price,
IceCreamComponents = IceCreamComponents
};
public XElement GetXElement => new("IceCream",
new XAttribute("Id", Id),
new XElement("IceCreamName", IceCreamName),
new XElement("Price", Price.ToString()),
new XElement("IceCreamComponents", Components.Select(x =>
new XElement("IceCreamComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}