PIbd-23_Starostin_I.K._Ship.../ShipyardFileImplement/Ship.cs

96 lines
3.4 KiB
C#

using ShipyardContracts.BindingModels;
using ShipyardContracts.ViewModels;
using ShipyardDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ShipyardFileImplement.Models
{
public class Ship : IShipModel
{
public int Id { get; private set; }
public string ShipName { 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)>? _ShipComponents = null;
public Dictionary<int, (IComponentModel, int)> ShipComponents
{
get
{
if (_ShipComponents == null)
{
var source = DataFileSingleton.GetInstance();
_ShipComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _ShipComponents;
}
}
public static Ship? Create(ShipBindingModel model)
{
if (model == null)
{
return null;
}
return new Ship()
{
Id = model.Id,
ShipName = model.ShipName,
Price = model.Price,
Components = model.ShipComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Ship? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Ship()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShipName = element.Element("ShipName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("ShipComponents")!.Elements("ShipComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShipBindingModel model)
{
if (model == null)
{
return;
}
ShipName = model.ShipName;
Price = model.Price;
Components = model.ShipComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_ShipComponents = null;
}
public ShipViewModel GetViewModel => new()
{
Id = Id,
ShipName = ShipName,
Price = Price,
ShipComponents = ShipComponents
};
public XElement GetXElement => new("Ship",
new XAttribute("Id", Id),
new XElement("ShipName", ShipName),
new XElement("Price", Price.ToString()),
new XElement("ShipComponents", Components.Select(x =>
new XElement("ShipComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}