PIbd-23_Mochalov_D.V._LawFirm/LawFirm/LawFirmFileImplement/Models/Document.cs
2023-04-23 23:05:06 +04:00

110 lines
3.4 KiB
C#

using LawFirmContracts.BindingModels;
using LawFirmContracts.ViewModels;
using LawFirmDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace LawFirmFileImplement.Models
{
[DataContract]
public class Document : IDocumentModel
{
[DataMember]
public string DocumentName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
[DataMember]
public int Id { get; private set; }
public Dictionary<int, int> Blanks { get; private set; } = new();
private Dictionary<int, (IBlankModel, int)>? _documentBlanks = null;
[DataMember]
public Dictionary<int, (IBlankModel, int)> DocumentBlanks
{
get
{
if (_documentBlanks == null)
{
var source = DataFileSingleton.GetInstance();
_documentBlanks = Blanks.ToDictionary(
x => x.Key,
y => ((source.Blanks.FirstOrDefault(z => z.Id == y.Key) as IBlankModel)!, y.Value)
);
}
return _documentBlanks;
}
}
public static Document? Create(DocumentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Document()
{
Id = model.Id,
DocumentName = model.DocumentName,
Price = model.Price,
Blanks = model.DocumentBlanks.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("DocumentName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Blanks = element.Element("DocumentBlanks")!.Elements("DocumentBlank").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;
Blanks = model.DocumentBlanks.ToDictionary(x => x.Key, x => x.Value.Item2);
_documentBlanks = null;
}
public DocumentViewModel GetViewModel => new()
{
Id = Id,
DocumentName = DocumentName,
Price = Price,
DocumentBlanks = DocumentBlanks
};
public XElement GetXElement => new(
"Document",
new XAttribute("Id", Id),
new XElement("DocumentName", DocumentName),
new XElement("Price", Price.ToString()),
new XElement("DocumentBlanks", Blanks.Select(x =>
new XElement("DocumentBlank",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}