using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
using RouteGuideDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RouteGuideContracts.BindingModels;
using RouteGuideContracts.ViewModels;
using MongoDB.Driver;
namespace RouteGuideMongoDBImplement.Models
{
///
/// Сущность "Маршрут"
///
public class Route : IRouteModel
{
///
/// Идентификатор
///
[BsonId]
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; private set; }
///
/// Название маршрута
///
[BsonRequired]
public string Name { get; private set; } = string.Empty;
///
/// Идентификатор транспорта
///
[BsonRequired]
[BsonElement("TransportId")]
public string? TransportId { get; private set; }
///
/// Сущность "Транспорт"
///
[BsonIgnoreIfNull]
[BsonIgnoreIfDefault]
public virtual Transport Transport { get; private set; } = new();
///
/// Коллекция остановок маршрута
///
[BsonElement("Stops")]
public Dictionary? Stops = new();
///
/// Коллекция остановок маршрута
///
[BsonIgnore]
private Dictionary, int)>? _routeStops = null;
///
/// Коллекция остановок маршрута
///
[BsonIgnore]
public Dictionary, int)>? RouteStops
{
get
{
if (_routeStops == null)
{
_routeStops = Stops?
.ToDictionary(recRS => recRS.Key, recRS => (recRS.Value.Stop as IStopModel, recRS.Value.Number));
}
return _routeStops;
}
}
///
/// Созданме модели
///
///
///
///
public static Route Create(RouteGuideDatabase context, RouteBindingModel model)
{
return new Route()
{
Name = model.Name,
TransportId = model.TransportId.ToString(),
Transport = context.Transport
.Find(Builders.Filter.Eq(x => x.Id, model.TransportId))
.FirstOrDefault(),
Stops = model.RouteStops.ToDictionary(
x => x.Key.ToString()!,
x => (context.Stops
.Find(Builders.Filter.Eq(y => y.Id, x.Key))
.FirstOrDefault(),
x.Value.Item2))
};
}
///
/// Изменение модели
///
///
public void Update(RouteBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
///
/// Получение модели
///
public RouteViewModel GetViewModel => new()
{
Id = Id!,
Name = Name,
TransportId = TransportId!,
RouteStops = RouteStops?
.ToDictionary(recRS => (object)recRS.Key, recRS => (new StopViewModel()
{
Id = (object)recRS.Value.Item1.Id!,
Name = recRS.Value.Item1.Name,
Street = recRS.Value.Item1.Street,
Number = recRS.Value.Item1.Number
} as IStopModel