using SecuritySystemContracts.BindingModels; using SecuritySystemContracts.ViewModels; using SecuritySystemDataModels.Models; using SecuritySystemFileImplement; using System.Xml.Linq; namespace AutomobilePlantFileImplement.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 MaxSecuresCount { get; private set; } public DateTime OpeningDate { get; private set; } public Dictionary Secures { get; private set; } = new(); private Dictionary? _shopSecures = null; public Dictionary ShopSecures { get { if (_shopSecures == null) { var source = DataFileSingleton.GetInstance(); _shopSecures = Secures.ToDictionary( x => x.Key, y => ((source.Secures.FirstOrDefault(z => z.Id == y.Key) as ISecureModel)!, y.Value) ); } return _shopSecures; } } public static Shop? Create(ShopBindingModel? model) { if (model == null) { return null; } return new Shop() { Id = model.Id, Name = model.Name, Address = model.Address, MaxSecuresCount = model.MaxSecuresCount, OpeningDate = model.OpeningDate, Secures = model.ShopSecures.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, MaxSecuresCount = Convert.ToInt32(element.Element("MaxSecuresCount")!.Value), OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), Secures = element.Element("ShopSecures")!.Elements("ShopSecure").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; MaxSecuresCount = model.MaxSecuresCount; OpeningDate = model.OpeningDate; if (model.ShopSecures.Count > 0) { Secures = model.ShopSecures.ToDictionary(x => x.Key, x => x.Value.Item2); _shopSecures = null; } } public ShopViewModel GetViewModel => new() { Id = Id, Name = Name, Address = Address, MaxSecuresCount = MaxSecuresCount, OpeningDate = OpeningDate, ShopSecures = ShopSecures, }; public XElement GetXElement => new( "Shop", new XAttribute("Id", Id), new XElement("Name", Name), new XElement("Address", Address), new XElement("MaxSecuresCount", MaxSecuresCount), new XElement("OpeningDate", OpeningDate.ToString()), new XElement("ShopSecures", Secures.Select(x => new XElement("ShopSecure", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }