Pibd-22_Presnyakova.V.V_Jew.../JewelryStoreFileImplement/Models/Jewel.cs
2023-02-19 21:02:22 +04:00

96 lines
3.2 KiB
C#

using JewelryStoreDataModels.Models;
using JewelryStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JewelryStoreContracts.BindingModels;
using System.Xml.Linq;
namespace JewelryStoreFileImplement.Models
{
public class Jewel: IJewelModel
{
public int Id { get; private set; }
public string JewelName { 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)> JewelComponents
{
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 Jewel? Create(JewelBindingModel model)
{
if (model == null)
{
return null;
}
return new Jewel()
{
Id = model.Id,
JewelName = model.JewelName,
Price = model.Price,
Components = model.JewelComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Jewel? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Jewel()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
JewelName = element.Element("JewelName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("JewelComponents")!.Elements("JewelComponent").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(JewelBindingModel model)
{
if (model == null)
{
return;
}
JewelName = model.JewelName;
Price = model.Price;
Components = model.JewelComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
_productComponents = null;
}
public JewelViewModel GetViewModel => new()
{
Id = Id,
JewelName = JewelName,
Price = Price,
JewelComponents = JewelComponents
};
public XElement GetXElement => new("Jewel",
new XAttribute("Id", Id),
new XElement("JewelName", JewelName),
new XElement("Price", Price.ToString()),
new XElement("JewelComponents", Components.Select(x =>new XElement("JewelComponent",new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}