PIbd-21_Pyatakov_K.M._Secure/Secure/SecureShopFileImplement/Models/Secure.cs
2023-03-09 12:31:36 +04:00

79 lines
3.0 KiB
C#

using SecureShopContracts.BindingModels;
using SecureShopContracts.ViewModels;
using SecureShopDataModels.Models;
using System.Xml.Linq;
namespace SecureShopFileImplement.Models
{
public class Secure : ISecureModel
{
public int Id { get; private set; }
public string SecureName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Facilitiess { get; private set; } = new();
private Dictionary<int, (IFacilitiesModel, int)>? _SecureFacilitiess = null;
public Dictionary<int, (IFacilitiesModel, int)> SecureFacilitiess
{
get
{
if (_SecureFacilitiess == null)
{
var source = DataFileSingleton.GetInstance();
_SecureFacilitiess = Facilitiess.ToDictionary(x => x.Key, y => ((source.Facilitiess.FirstOrDefault(z => z.Id == y.Key) as IFacilitiesModel)!, y.Value));
}
return _SecureFacilitiess;
}
}
public static Secure? Create(SecureBindingModel model)
{
if (model == null)
{
return null;
}
return new Secure()
{
Id = model.Id,
SecureName = model.SecureName,
Price = model.Price,
Facilitiess = model.SecureFacilitiess.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Secure? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Secure()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SecureName = element.Element("SecureName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Facilitiess = element.Element("SecureFacilitiess")!.Elements("SecureFacilities").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(SecureBindingModel model)
{
if (model == null)
{
return;
}
SecureName = model.SecureName;
Price = model.Price;
Facilitiess = model.SecureFacilitiess.ToDictionary(x => x.Key, x => x.Value.Item2);
_SecureFacilitiess = null;
}
public SecureViewModel GetViewModel => new()
{
Id = Id,
SecureName = SecureName,
Price = Price,
SecureFacilitiess = SecureFacilitiess
};
public XElement GetXElement => new("Secure", new XAttribute("Id", Id), new XElement("SecureName", SecureName), new XElement("Price", Price.ToString()), new XElement("SecureFacilitiess", Facilitiess.Select(x => new XElement("SecureFacilities", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()));
}
}