PIbd-21_RazubaevSM_Plumbing.../PlumbingRepair/PlumbingRepairFileImplement/Models/Shop.cs

107 lines
3.8 KiB
C#

using PlumbingRepairContracts.BindingModels;
using PlumbingRepairContracts.ViewModels;
using PlumbingRepairDataModels.Models;
using System.Xml.Linq;
namespace PlumbingRepairFileImplement.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> Works { get; private set; } = new();
private Dictionary<int, (IWorkModel, int)>? _shopWorks = null;
public Dictionary<int, (IWorkModel, int)> ShopWorks
{
get
{
if (_shopWorks == null)
{
var source = DataFileSingleton.GetInstance();
_shopWorks = Works.ToDictionary(x => x.Key,
y => ((source.Works.FirstOrDefault(z => z.Id == y.Key) as IWorkModel)!, y.Value));
}
return _shopWorks;
}
}
public int maxCountWorks { 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,
Works = model.ShopWorks.ToDictionary(x => x.Key, x => x.Value.Item2),
maxCountWorks= model.maxCountWorks,
};
}
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),
maxCountWorks = Convert.ToInt32(element.Element("maxCountWorks")!.Value),
Works = element.Element("ShopWorks")!.Elements("ShopWork")
.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;
Works = model.ShopWorks.ToDictionary(x => x.Key, x => x.Value.Item2);
maxCountWorks = model.maxCountWorks;
_shopWorks = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopWorks = ShopWorks,
maxCountWorks = maxCountWorks,
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("maxCountWorks", maxCountWorks.ToString()),
new XElement("ShopWorks",
Works.Select(x => new XElement("ShopWork",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}