PIbd21_Makarov_DV_FlowerShop/FlowerShop/FlowerShopFileImplement/Models/Shop.cs

89 lines
2.9 KiB
C#
Raw Normal View History

2024-04-19 02:23:50 +04:00
using FlowerShopContracts.BindingModels;
using FlowerShopContracts.ViewModels;
using FlowerShopDataModels.Models;
using System.Xml.Linq;
namespace FlowerShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, int> Flowers { get; private set; } = new();
private Dictionary<int, (IFlowerModel, int)> _shopFlowers = null;
public Dictionary<int, (IFlowerModel, int)> ShopFlowers
{
get
{
if (_shopFlowers == null)
{
var source = DataFileSingleton.GetInstance();
_shopFlowers = Flowers.ToDictionary(x => x.Key,
y => ((source.Flowers.FirstOrDefault(z => z.Id == y.Key) as IFlowerModel)!, y.Value));
}
return _shopFlowers;
}
}
public int MaximumFlowers { get; private set; }
public static Shop? Create(ShopBindingModel model)
{
if (model == null) return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
Flowers = model.ShopFlowers.ToDictionary(x => x.Key, x => x.Value.Item2),
MaximumFlowers = model.MaximumFlowers,
};
}
public static Shop? Create(XElement element)
{
if (element == null) return null;
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
MaximumFlowers = Convert.ToInt32(element.Element("MaximumFlowers")!.Value),
Flowers = element.Element("ShopFlowers")!.Elements("ShopFlower")
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel? model)
{
if (model == null) return;
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
MaximumFlowers = model.MaximumFlowers;
Flowers = model.ShopFlowers.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopFlowers = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
MaximumFlowers = MaximumFlowers,
ShopFlowers = ShopFlowers,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("MaximumFlowers", MaximumFlowers.ToString()),
new XElement("ShopFlowers",
Flowers.Select(x => new XElement("ShopFlower",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}