using CarRepairShopContracts.BindingModels; using CarRepairShopContracts.ViewModels; using CarRepairShopDataModels.Models; using System.Xml.Linq; namespace CarRepairShopFileImplement.Models { public class Shop : IShopModel { public int Id { get; private set; } public string ShopName { get; private set; } = string.Empty; public string Address { get; private set; } = string.Empty; public DateTime DateOpening { get; private set; } public Dictionary Repairs { get; private set; } = new(); private Dictionary? _shopRepairs = null; public Dictionary ShopRepairs { get { if (_shopRepairs == null) { var source = DataFileSingleton.GetInstance(); _shopRepairs = Repairs.ToDictionary(x => x.Key, y => ((source.Repairs.FirstOrDefault(z => z.Id == y.Key) as IRepairModel)!, y.Value)); } return _shopRepairs; } } public int RepairMaxAmount { get; private set; } 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, Repairs = model.ShopRepairs.ToDictionary(x => x.Key, x => x.Value.Item2), RepairMaxAmount = model.RepairMaxAmount }; } 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, DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), RepairMaxAmount = Convert.ToInt32(element.Element("RepairMaxAmount")!.Value), Repairs = element.Element("ShopRepairs")!.Elements("ShopRepair") .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; RepairMaxAmount = model.RepairMaxAmount; Repairs = model.ShopRepairs.ToDictionary(x => x.Key, x => x.Value.Item2); _shopRepairs = null; } public ShopViewModel GetViewModel => new() { Id = Id, ShopName = ShopName, Address = Address, DateOpening = DateOpening, ShopRepairs = ShopRepairs, RepairMaxAmount = RepairMaxAmount }; public XElement GetXElement => new("Shop", new XAttribute("Id", Id), new XElement("ShopName", ShopName), new XElement("Address", Address), new XElement("DateOpening", DateOpening.ToString()), new XElement("RepairMaxAmount", RepairMaxAmount.ToString()), new XElement("ShopRepairs", Repairs.Select(x => new XElement("ShopRepair", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); } }