PIbd-23_Minhasapov_R.H._Aut.../AutomobilePlant/AutomobilePlantFileImplement/Models/Shop.cs

123 lines
3.9 KiB
C#

using AutomobilePlantContracts.BindingModels;
using AutomobilePlantContracts.ViewModels;
using AutomobilePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace AutomobilePlantFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public int MaxCountCars { get; private set; }
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Cars { get; private set; } = new();
private Dictionary<int, (ICarModel, int)>? _shopCars = null;
public Dictionary<int, (ICarModel, int)> ShopCars
{
get
{
if (_shopCars == null)
{
var source = DataFileSingleton.GetInstance();
_shopCars = Cars.ToDictionary(
x => x.Key,
y => ((source.Cars.FirstOrDefault(z => z.Id == y.Key) as ICarModel)!, y.Value)
);
}
return _shopCars;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
Name = model.Name,
Address = model.Address,
MaxCountCars = model.MaxCountCars,
OpeningDate = model.OpeningDate,
Cars = model.ShopCars.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Name = element.Element("Name")!.Value,
Address = element.Element("Address")!.Value,
MaxCountCars = Convert.ToInt32(element.Element("MaxCountCars")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Cars = element.Element("ShopCars")!.Elements("ShopCar").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCountCars = model.MaxCountCars;
if (model.ShopCars.Count > 0)
{
Cars = model.ShopCars.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopCars = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Address = Address,
OpeningDate = OpeningDate,
ShopCars = ShopCars,
MaxCountCars = MaxCountCars
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("Name", Name),
new XElement("Address", Address),
new XElement("MaxCountCars", MaxCountCars),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopCars", Cars.Select(x =>
new XElement("ShopCar",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}