ISEbd-21_Zinovev_V.V._Furni.../FurnitureAssembly/FurnitureAssemblyFileImplement/Models/Furniture.cs
2024-06-17 18:47:33 +04:00

110 lines
3.6 KiB
C#

using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.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 FurnitureAssemblyFileImplement.Models
{
[DataContract]
public class Furniture
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string FurnitureName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
public Dictionary<int, int> Workpieces { get; private set; } = new();
private Dictionary<int, (IWorkpieceModel, int)>? _furnitureWorkpieces = null;
[DataMember]
public Dictionary<int, (IWorkpieceModel, int)> FurnitureWorkpieces
{
get
{
if (_furnitureWorkpieces == null)
{
var source = DataFileSingleton.GetInstance();
_furnitureWorkpieces = Workpieces.ToDictionary(x => x.Key,
y => ((source.Workpieces.FirstOrDefault(z => z.Id == y.Key) as IWorkpieceModel)!, y.Value));
}
return _furnitureWorkpieces;
}
}
public static Furniture? Create(FurnitureBindingModel model)
{
if (model == null)
{
return null;
}
return new Furniture()
{
Id = model.Id,
FurnitureName = model.FurnitureName,
Price = model.Price,
Workpieces = model.FurnitureWorkpieces.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Furniture? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Furniture()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
FurnitureName = element.Element("FurnitureName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Workpieces = element.Element("FurnitureWorkpieces")!.Elements("FurnitureWorkpieces").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
y => Convert.ToInt32(y.Element("Value")?.Value))
};
}
public void Update(FurnitureBindingModel model)
{
if (model == null)
{
return;
}
FurnitureName = model.FurnitureName;
Price = model.Price;
Workpieces = model.FurnitureWorkpieces.ToDictionary(x => x.Key, x => x.Value.Item2);
_furnitureWorkpieces = null;
}
public FurnitureViewModel GetViewModel => new()
{
Id = Id,
FurnitureName = FurnitureName,
Price = Price,
FurnitureWorkpieces = FurnitureWorkpieces
};
public XElement GetXElement => new("Furniture",
new XAttribute("Id", Id),
new XElement("FurnitureName", FurnitureName),
new XElement("Price", Price.ToString()),
new XElement("FurnitureWorkpieces", Workpieces.Select(
x => new XElement("FurnitureWorkpieces",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
).ToArray()));
}
}