96 lines
3.3 KiB
C#
Raw Normal View History

2023-03-07 14:40:00 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using SecuritySystemDataModels.Models;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement;
namespace SecuritySystemFileImplement.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> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _SecureComponents = null;
public Dictionary<int, (IComponentModel, int)> SecureComponents
{
get
{
if (_SecureComponents == null)
{
var source = DataFileSingleton.GetInstance();
_SecureComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _SecureComponents;
}
}
public static Secure? Create(SecureBindingModel model)
{
if (model == null)
{
return null;
}
return new Secure()
{
Id = model.Id,
SecureName = model.SecureName,
Price = model.Price,
Components = model.SecureComponents.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),
Components =
element.Element("SecureComponents")!.Elements("SecureComponent")
.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;
Components = model.SecureComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_SecureComponents = null;
}
public SecureViewModel GetViewModel => new()
{
Id = Id,
SecureName = SecureName,
Price = Price,
SecureComponents = SecureComponents
};
public XElement GetXElement => new("Secure",
new XAttribute("Id", Id),
new XElement("SecureName", SecureName),
new XElement("Price", Price.ToString()),
new XElement("SecureComponents", Components.Select(x =>
new XElement("SecureComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}