PIbd-22_Chernyshev_G.J._30_.../GarmentFactoryFileImplement/Models/Textile.cs

100 lines
3.3 KiB
C#
Raw Normal View History

2024-03-16 20:47:16 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GarmentFactoryContracts.BindingModels;
using GarmentFactoryContracts.ViewModels;
using GarmentFactoryDataModels.Models;
using System.Xml.Linq;
using System.Runtime.Serialization;
2024-03-16 20:47:16 +04:00
namespace GarmentFactoryFileImplement.Models
{
[DataContract]
public class Textile : ITextileModel
2024-03-16 20:47:16 +04:00
{
[DataMember]
public int Id { get; private set; }
[DataMember]
public string TextileName { get; private set; } = string.Empty;
[DataMember]
public double Price { get; private set; }
2024-03-16 20:47:16 +04:00
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _textileComponents = null;
[DataMember]
public Dictionary<int, (IComponentModel, int)> TextileComponents
2024-03-16 20:47:16 +04:00
{
get
{
if (_textileComponents == null)
{
var source = DataFileSingleton.GetInstance();
_textileComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _textileComponents;
}
}
public static Textile? Create(TextileBindingModel model)
{
if (model == null)
{
return null;
}
return new Textile()
{
Id = model.Id,
TextileName = model.TextileName,
Price = model.Price,
Components = model.TextileComponents.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Textile? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Textile()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
TextileName = element.Element("TextileName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components = element.Element("TextileComponents")!.Elements("TextileComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(TextileBindingModel model)
{
if (model == null)
{
return;
}
TextileName = model.TextileName;
Price = model.Price;
Components = model.TextileComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_textileComponents = null;
}
public TextileViewModel GetViewModel => new()
{
Id = Id,
TextileName = TextileName,
Price = Price,
TextileComponents = TextileComponents
};
public XElement GetXElement => new("Textile",
new XAttribute("Id", Id),
new XElement("TextileName", TextileName),
new XElement("Price", Price.ToString()),
new XElement("TextileComponents", Components.Select(x =>
new XElement("TextileComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}