using FlowerShopContracts.BindingModels; using FlowerShopContracts.ViewModels; using FlowerShopDataModels.Models; using System.Xml.Linq; namespace FlowerShopFileImplement.Models { public class Shop : IShopModel { public int Id { get; private set; } public string Name { get; private set; } = string.Empty; public string Address { get; private set; } = string.Empty; public int MaxCountBouquets { get; private set; } public DateTime OpeningDate { get; private set; } public Dictionary Bouquets { get; private set; } = new(); private Dictionary? _shopBouquets = null; public Dictionary ShopBouquets { get { if (_shopBouquets == null) { var source = DataFileSingleton.GetInstance(); _shopBouquets = Bouquets.ToDictionary( x => x.Key, y => ((source.Bouquets.FirstOrDefault(z => z.Id == y.Key) as IBouquetModel)!, y.Value) ); } return _shopBouquets; } } public static Shop? Create(ShopBindingModel? model) { if (model == null) { return null; } return new Shop() { Id = model.Id, Name = model.Name, Address = model.Address, MaxCountBouquets = model.MaxCountBouquets, OpeningDate = model.OpeningDate, Bouquets = model.ShopBouquets.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), Name = element.Element("Name")!.Value, Address = element.Element("Address")!.Value, MaxCountBouquets = Convert.ToInt32(element.Element("MaxCountBouquets")!.Value), OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), Bouquets = element.Element("ShopBouquets")!.Elements("ShopBouquet").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; OpeningDate = model.OpeningDate; MaxCountBouquets = model.MaxCountBouquets; if (model.ShopBouquets.Count > 0) { Bouquets = model.ShopBouquets.ToDictionary(x => x.Key, x => x.Value.Item2); _shopBouquets = null; } } public ShopViewModel GetViewModel => new() { Id = Id, Name = Name, Address = Address, OpeningDate = OpeningDate, ShopBouquets = ShopBouquets, MaxCountBouquets = MaxCountBouquets }; public XElement GetXElement => new( "Shop", new XAttribute("Id", Id), new XElement("Name", Name), new XElement("Address", Address), new XElement("MaxCountBouquets", MaxCountBouquets), new XElement("OpeningDate", OpeningDate.ToString()), new XElement("ShopBouquets", Bouquets.Select(x => new XElement("ShopBouquet", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray()) ); } }