using System.Xml.Linq; using SushiBarContracts.BindingModels; using SushiBarContracts.ViewModels; using SushiBarDataModels.Models; namespace SushiBarFileImplement.Models { public class Store : IStoreModel { public int Id { get; private init; } public string StoreName { get; private set; } = string.Empty; public string StoreAddress { get; private set; } = string.Empty; public DateTime OpeningDate { get; private set; } public int maxSushi { get; private set; } private Dictionary _sushi = new(); public Dictionary Sushis { get { var source = DataFileSingleton.GetInstance(); return _sushi.ToDictionary(i => i.Key, i => (source.Sushis.FirstOrDefault(z => z.Id == i.Key)! as ISushiModel, i.Value)); } private init => Sushis = value; } public static Store? Create(StoreBindingModel? model) { if (model == null) { return null; } return new Store() { Id = model.Id, StoreName = model.StoreName, OpeningDate = model.OpeningDate, StoreAddress = model.StoreAddress, _sushi = model.Sushis .ToDictionary(x => x.Key, x => x.Value.Item2), maxSushi = model.maxSushi }; } public static Store? Create(XElement? element) { if (element == null) { return null; } return new Store() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), StoreName = element.Element("StoreName")!.Value, StoreAddress = element.Element("StoreAddress")!.Value, maxSushi = Convert.ToInt32(element.Element("MaxSushi")!.Value), _sushi = element.Element("Sushis") !.Elements("Sushi") .ToDictionary( x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value) ) }; } public void Update(StoreBindingModel? model) { if (model == null) { return; } StoreName = model.StoreName; StoreAddress = model.StoreAddress; _sushi = model.Sushis .ToDictionary(x => x.Key, x => x.Value.Item2); maxSushi = model.maxSushi; } public StoreViewModel GetViewModel => new() { Id = Id, StoreName = StoreName, Sushis = Sushis, StoreAddress = StoreAddress, maxSushi = maxSushi }; public XElement GetXElement => new("Store", new XAttribute("Id", Id), new XElement("StoreName", StoreName), new XElement("StoreAddress", StoreAddress), new XElement("MaxSushi", maxSushi), new XElement("Sushis", _sushi.Select(x => new XElement("Sushi", new XElement("Key", x.Key), new XElement("Value", x.Value)) ).ToArray()) ); } }