PIbd-23_Elatomtsev_L.K._Con.../Confectionery/ConfectioneryFileImplement/Models/Shop.cs
2024-06-20 06:10:16 +04:00

105 lines
2.9 KiB
C#

using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Models;
using System.Xml.Linq;
namespace ConfectioneryFileImplement.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 DateOpen { get; private set; }
public int MaxCapacity { get; private set; }
public Dictionary<int, int> Pastries { get; private set; } = new();
private Dictionary<int, (IPastryModel, int)>? _shopPastries = null;
public Dictionary<int, (IPastryModel, int)> ShopPastries
{
get
{
if (_shopPastries == null)
{
var source = DataFileSingleton.GetInstance();
_shopPastries = Pastries.ToDictionary(
x => x.Key, y => ((source.Pastries
.FirstOrDefault(z => z.Id == y.Key) as IPastryModel)!,
y.Value));
}
return _shopPastries;
}
}
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
MaxCapacity = model.MaxCapacity,
Pastries = model.ShopPastries.ToDictionary(
x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
MaxCapacity = Convert.ToInt32(
element.Element("MaxCapacity")!.Value),
DateOpen = Convert.ToDateTime(
element.Element("DateOpen")!.Value),
Pastries = element
.Element("ShopPastries")!.Elements("ShopPastry")
.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;
DateOpen = model.DateOpen;
MaxCapacity = model.MaxCapacity;
if (model.ShopPastries.Count > 0)
{
Pastries = model.ShopPastries
.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopPastries = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
MaxCapacity = MaxCapacity,
ShopPastries = ShopPastries
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpen", DateOpen),
new XElement("MaxCapacity", MaxCapacity),
new XElement("ShopPastries", Pastries
.Select(x => new XElement("ShopPastry",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}