PIbd-22_Petrushin_E.A._LawFirm/LawFirm/AbstractLawFirmFileImpliment/Models/Document.cs

104 lines
3.5 KiB
C#
Raw Normal View History

2024-03-12 21:53:02 +04:00
using AbstractLawFirmContracts.BindingModels;
using AbstractLawFirmContracts.ViewModels;
using AbstractLawFirmDataModels.Models;
using AbstractLawFirmFileImpliment;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AbstractLawFirmFileImplement.Models
{
public class Document : IDocumentModel
{
public int Id { get; private set; }
public string DocumentName { 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)>? _productComponents =
null;
public Dictionary<int, (IComponentModel, int)> ProductComponents
{
get
{
if (_productComponents == null)
{
var source = DataFileSingleton.GetInstance();
_productComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _productComponents;
}
}
public static Document? Create(DocumentBindingModel model)
{
if (model == null)
{
return null;
}
return new Document()
{
Id = model.Id,
DocumentName = model.DocumentName,
Price = model.Price,
Components = model.DocumentComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Document? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Document()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
DocumentName = element.Element("ProductName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("ProductComponents")!.Elements("ProductComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(DocumentBindingModel model)
{
if (model == null)
{
return;
}
DocumentName = model.DocumentName;
Price = model.Price;
Components = model.DocumentComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_productComponents = null;
}
public DocumentViewModel GetViewModel => new()
{
Id = Id,
DocumentName = DocumentName,
Price = Price,
DocumentComponents = ProductComponents
};
public XElement GetXElement => new("Product",
new XAttribute("Id", Id),
new XElement("ProductName", DocumentName),
new XElement("Price", Price.ToString()),
new XElement("ProductComponents", Components.Select(x =>
new XElement("ProductComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
public Dictionary<int, (IComponentModel, int)> DocumentComponents => throw new NotImplementedException();
}
}