using SushiBarContracts.BindingModel; using SushiBarContracts.ViewModels; using SushiBarDataModels; using SushiBarDataModels.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace SushiBarFileImplement.Models { public class Shop : IShopModel { public int Id { get; private set; } public string ShopName { get; private set; } public string Address { get; private set; } public DateTime DateOpening { get; private set; } public int MaxCountSushis { get; private set; } public Dictionary Sushis { get; private set; } = new(); private Dictionary? _shopSushis = null; public Dictionary ShopSushis { get { if (_shopSushis == null) { var source = DataFileSingleton.GetInstance(); _shopSushis = Sushis.ToDictionary(x => x.Key, y => ((source.Sushis.FirstOrDefault(z => z.Id == y.Key) as ISushiModel)!, y.Value)); } return _shopSushis; } } public static Shop? Create(ShopBindingModel model) { if (model == null) { return null; } return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, MaxCountSushis = model.MaxCountSushis, Sushis = model.ShopSushis.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, MaxCountSushis = Convert.ToInt32(element.Element("MaxCountSushis")!.Value), DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), Sushis = element.Element("ShopSushis")!.Elements("ShopSushis").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; MaxCountSushis = model.MaxCountSushis; if (model.ShopSushis.Count > 0) { Sushis = model.ShopSushis.ToDictionary(x => x.Key, x => x.Value.Item2); _shopSushis = null; } } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, MaxCountSushis = MaxCountSushis, ShopSushis = ShopSushis }; public XElement GetXElement => new XElement("Shop", new XAttribute("Id", Id), new XElement("ShopName", ShopName), new XElement("Address", Address), new XElement("DateOpening", DateOpening), new XElement("MaxCountSushis", MaxCountSushis), new XElement("ShopSushis", Sushis.Select(x => new XElement("ShopSushis", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }