using ComputersShopContracts.BindingModels; using ComputersShopContracts.ViewModels; using ComputersShopDataModels.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace ComputersShopFileImplements.Models { public class Shop: IShopModel { public int Id { get; set; } public string ShopName { get; set;} public string Address { get; set;} public DateTime DateOpen { get; set;} public int MaxCount { get; set;} public Dictionary Computers { get; private set; } = new(); private Dictionary? _shopComputers = null; public Dictionary ShopComputers { get { if (_shopComputers == null) { var source = DataFileSingleton.GetInstance(); _shopComputers = Computers.ToDictionary(x => x.Key, y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!, y.Value)); } return _shopComputers; } } public static Shop? Create(ShopBindingModel model) { if (model == null) { return null; } return new Shop() { Id = model.Id, ShopName = model.ShopName, Address = model.Address, MaxCount = model.MaxCount, DateOpen = model.DateOpen, Computers = model.ShopComputers.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), MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value), ShopName = element.Element("ShopName")!.Value, Address = element.Element("Address")!.Value, DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), Computers = element.Element("ShopComputers")!.Elements("ShopComputer").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; MaxCount = model.MaxCount; DateOpen = model.DateOpen; if (model.ShopComputers.Count > 0) { Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2); _shopComputers = null; } } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, MaxCount = MaxCount, DateOpen = DateOpen, ShopComputers = ShopComputers }; public XElement GetXElement => new("Shop", new XAttribute("Id", Id), new XElement("ShopName", ShopName), new XElement("Address", Address.ToString()), new XElement("MaxCount", MaxCount.ToString()), new XElement("DateOpen", DateOpen.ToString()), new XElement("ShopComputers", Computers.Select(x => new XElement("ShopComputer", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }