using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TravelCompanyDataModels.Models; using TravelCompanyContracts.ViewModels; using TravelCompanyContracts.BindingModels; using System.Xml.Linq; namespace TravelCompanyFileImplement.Models { public class Travel : ITravelModel { public int Id { get; private set; } public string TravelName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Conditions { get; private set; } = new(); private Dictionary? _travelConditions = null; public Dictionary TravelConditions { get { if (_travelConditions == null) { var source = DataFileSingleton.GetInstance(); _travelConditions = Conditions.ToDictionary(x => x.Key, y => ((source.Conditions.FirstOrDefault(z => z.Id == y.Key) as IConditionModel)!,y.Value)); } return _travelConditions; } } public static Travel? Create(TravelBindingModel model) { if (model == null) { return null; } return new Travel() { Id = model.Id, TravelName = model.TravelName, Price = model.Price, Conditions = model.TravelConditions.ToDictionary(x => x.Key, x=> x.Value.Item2) }; } public static Travel? Create(XElement element) { if (element == null) { return null; } return new Travel() { Id = Convert.ToInt32(element.Attribute("Id")!.Value), TravelName = element.Element("TravelName")!.Value, Price = Convert.ToDouble(element.Element("Price")!.Value), Conditions = element.Element("TravelConditions")!.Elements("TravelCondition").ToDictionary(x =>Convert.ToInt32(x.Element("Key")?.Value), x =>Convert.ToInt32(x.Element("Value")?.Value)) }; } public void Update(TravelBindingModel model) { if (model == null) { return; } TravelName = model.TravelName; Price = model.Price; Conditions = model.TravelConditions.ToDictionary(x => x.Key, x =>x.Value.Item2); _travelConditions = null; } public TravelViewModel GetViewModel => new() { Id = Id, TravelName = TravelName, Price = Price, TravelConditions = TravelConditions }; public XElement GetXElement => new("Travel", new XAttribute("Id", Id), new XElement("TravelName", TravelName), new XElement("Price", Price.ToString()), new XElement("TravelConditions", Conditions.Select(x => new XElement("TravelCondition", new XElement("Key", x.Key), new XElement("Value", x.Value))) .ToArray())); } }