PIbd-22_Chernyshev_G.J._30_.../GarmentFactoryFileImplement/Models/Textile.cs
2024-03-16 20:47:16 +04:00

90 lines
3.3 KiB
C#

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;
namespace GarmentFactoryFileImplement.Models
{
public class Textile : ITextileModel
{
public int Id { get; private set; }
public string TextileName { 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)>? _textileComponents = null;
public Dictionary<int, (IComponentModel, int)> TextileComponents
{
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()));
}
}