PIbd-21_Balberova_D.N._Sush.../SushiBar/SushiBarFileImplement/Models/Shop.cs

108 lines
3.8 KiB
C#
Raw Normal View History


using SushiBarContracts.BindingModels;
using SushiBarContracts.ViewModels;
using SushiBarDataModels.Models;
using System.Reflection.Metadata;
using System.Xml.Linq;
namespace SushiBarFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public int MaxCountSushi { get; private set; }
public Dictionary<int, int> CountSushi
{
get;
private set;
} = new();
private Dictionary<int, (ISushiModel, int)>? _shopSushi = null;
public Dictionary<int, (ISushiModel, int)> ListSushi
{
get
{
if (_shopSushi == null)
{
var source = DataFileSingleton.GetInstance();
_shopSushi =
CountSushi.ToDictionary(x => x.Key,
y => ((source.ListSushi.FirstOrDefault(z => z.Id == y.Key) as ISushiModel)!, y.Value));
}
return _shopSushi;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
MaxCountSushi = model.MaxCountSushi,
DateOpening = model.DateOpening,
CountSushi = model.ListSushi.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaxCountSushi = Convert.ToInt32(element.Element("MaxCountSushi")!.Value),
CountSushi = element.Element("ListSushi")!.Elements("Sushi").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaxCountSushi = model.MaxCountSushi;
CountSushi = model.ListSushi.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopSushi = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
ListSushi = ListSushi,
DateOpening = DateOpening,
MaxCountSushi = MaxCountSushi,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening),
new XElement("MaxCountSushi", MaxCountSushi),
new XElement("ListSushi", CountSushi
.Select(x => new XElement("Sushi",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
).ToArray()));
}
}