aleksandr chegodaev 093b43457b lab2
2024-04-13 02:05:00 +04:00

96 lines
3.1 KiB
C#

using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Models
{
public class Law : ILawModel
{
public int Id { get; private set; }
public string LawName { 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)>? _LawComponents = null;
public Dictionary<int, (IComponentModel, int)> LawComponents
{
get
{
if (_LawComponents == null)
{
var source = DataFileSingleton.GetInstance();
_LawComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _LawComponents;
}
}
public static Law? Create(LawBindingModel model)
{
if (model == null)
{
return null;
}
return new Law()
{
Id = model.Id,
LawName = model.LawName,
Price = model.Price,
Components = model.LawComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Law? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Law()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
LawName = element.Element("LawName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("LawComponents")!.Elements("LawComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(LawBindingModel model)
{
if (model == null)
{
return;
}
LawName = model.LawName;
Price = model.Price;
Components = model.LawComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_LawComponents = null;
}
public LawViewModel GetViewModel => new()
{
Id = Id,
LawName = LawName,
Price = Price,
LawComponents = LawComponents
};
public XElement GetXElement => new("Law",
new XAttribute("Id", Id),
new XElement("LawName", LawName),
new XElement("Price", Price.ToString()),
new XElement("LawComponents", Components.Select(x => new XElement("LawComponent", new XElement("Key", x.Key), new XElement("Value", x.Value)))
.ToArray()));
}
}