84 lines
3.4 KiB
C#
84 lines
3.4 KiB
C#
using DinerContracts.BindingModels;
|
|
using DinerContracts.ViewModels;
|
|
using DinerDataModels.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Runtime.InteropServices;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Xml.Linq;
|
|
using System.Xml.XPath;
|
|
|
|
namespace DinerFileImplement.Models
|
|
{
|
|
internal class Snack : ISnackModel
|
|
{
|
|
public string ProductName { 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, (IFoodModel, int)>? _productComponents = null;
|
|
public Dictionary<int, (IFoodModel, int)> ProductComponents
|
|
{
|
|
get
|
|
{
|
|
if (_productComponents == null) {
|
|
var source = DataFileSingleton.GetInstance();
|
|
_productComponents = Components.ToDictionary(x => x.Key, y => ((source.Foods.FirstOrDefault(z => z.ID ==
|
|
y.Key) as IFoodModel)!, y.Value));
|
|
}
|
|
return _productComponents;
|
|
}
|
|
}
|
|
|
|
public static Snack? Create(SnackBindingModel? model)
|
|
{
|
|
if (model == null) return null;
|
|
return new Snack()
|
|
{
|
|
ID = model.ID,
|
|
ProductName = model.ProductName,
|
|
Price = model.Price,
|
|
Components = model.ProductComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
|
|
};
|
|
}
|
|
public static Snack? Create(XElement element)
|
|
{
|
|
if (element == null) return null;
|
|
return new Snack()
|
|
{
|
|
ID = Convert.ToInt32(element.Attribute("ID")!.Value),
|
|
ProductName = element.Element("ProductName")!.Value,
|
|
Price = Convert.ToDouble(element.Element("Price")!.Value),
|
|
Components = element.Element("ProductComponents")!.Elements("ProductComponent")
|
|
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
|
|
};
|
|
}
|
|
public void Update(SnackBindingModel? model)
|
|
{
|
|
if (model == null) return;
|
|
ProductName = model.ProductName;
|
|
Price = model.Price;
|
|
Components = model.ProductComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
|
|
_productComponents = null;
|
|
}
|
|
public SnackViewModel GetViewModel => new()
|
|
{
|
|
ID = ID,
|
|
ProductName = ProductName,
|
|
Price = Price,
|
|
ProductComponents = ProductComponents
|
|
};
|
|
public XElement GetXElement => new("Snack", new XAttribute("ID", ID),
|
|
new XElement("ProductName", ProductName),
|
|
new XElement("Price", Price.ToString()),
|
|
new XElement("ProductComponents", Components.Select(x => new XElement("ProductComponent",
|
|
new XElement("Key", x.Key),
|
|
new XElement("Value", x.Value))).ToArray()));
|
|
}
|
|
}
|