ISEbd-21_Agliullov.D.A._Con.../ConfectionaryFileImplement/Shop.cs

110 lines
3.8 KiB
C#
Raw Normal View History

2023-02-15 05:01:38 +04:00
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels;
using ConfectioneryDataModels.Models;
using System.Xml.Linq;
namespace ConfectioneryFileImplement
{
public class Shop : IShopModel
{
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public int MaxCountPastries { get; private set; }
2023-02-15 05:01:38 +04:00
public DateTime DateOpening { get; private set; }
public Dictionary<int, int> CountPastries { get; private set; } = new();
private Dictionary<int, (IPastryModel, int)>? _cachedPastries = null;
public Dictionary<int, (IPastryModel, int)> Pastries
{
get
{
if (_cachedPastries == null)
{
var source = DataFileSingleton.GetInstance();
_cachedPastries = CountPastries
.ToDictionary(x => x.Key, x => (source.Pastries
.FirstOrDefault(y => y.Id == x.Key)! as IPastryModel, x.Value));
}
return _cachedPastries;
}
}
public int Id { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
DateOpening = model.DateOpening,
MaxCountPastries = model.MaxCountPastries,
2023-02-15 05:01:38 +04:00
CountPastries = new()
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Name = element.Element("Name")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaxCountPastries = Convert.ToInt32(element.Element("MaxCountPastries")!.Value),
CountPastries = element.Element("CountPastries")!.Elements("CountPastry")
2023-02-15 05:01:38 +04:00
.ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
DateOpening = model.DateOpening;
CountPastries = model.Pastries.ToDictionary(x => x.Key, x => x.Value.Item2);
_cachedPastries = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
Pastries = Pastries,
DateOpening = DateOpening,
MaxCountPastries = MaxCountPastries,
2023-02-15 05:01:38 +04:00
};
public XElement GetXElement => new("Shop",
2023-02-15 05:01:38 +04:00
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening),
new XElement("MaxCountPastries", MaxCountPastries),
2023-02-15 05:01:38 +04:00
new XElement("CountPastries", CountPastries
.Select(x => new XElement("CountPastry",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
))
);
}
}