PIbd-23_Nevaeva_K.A._Travel.../TravelCompany/TravelCompanyFileImplement/Implements/TravelStorage.cs

86 lines
2.7 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels;
using TravelCompanyContracts.SearchModels;
using TravelCompanyContracts.StoragesContracts;
using TravelCompanyContracts.ViewModels;
using TravelCompanyFileImplement.Models;
namespace TravelCompanyFileImplement.Implements
{
public class TravelStorage : ITravelStorage
{
private readonly DataFileSingleton _source;
public TravelStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<TravelViewModel> GetFullList()
{
return _source.Travels
.Select(x => x.GetViewModel)
.ToList();
}
public List<TravelViewModel> GetFilteredList(TravelSearchModel model)
{
if (string.IsNullOrEmpty(model.TravelName))
{
return new();
}
return _source.Travels
.Where(x => x.TravelName.Contains(model.TravelName))
.Select(x => x.GetViewModel)
.ToList();
}
public TravelViewModel? GetElement(TravelSearchModel model)
{
if (string.IsNullOrEmpty(model.TravelName) && !model.Id.HasValue)
{
return null;
}
return _source.Travels
.FirstOrDefault(x => (x.TravelName == model.TravelName && !string.IsNullOrEmpty(model.TravelName) ) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public TravelViewModel? Insert(TravelBindingModel model)
{
model.Id = _source.Travels.Count > 0 ? _source.Travels.Max(x => x.Id) + 1 : 1;
var newTravel = Travel.Create(model);
if (newTravel == null)
{
return null;
}
_source.Travels.Add(newTravel);
_source.SaveTravels();
return newTravel.GetViewModel;
}
public TravelViewModel? Update(TravelBindingModel model)
{
var travel = _source.Travels.FirstOrDefault(x => x.Id == model.Id);
if (travel == null)
{
return null;
}
travel.Update(model);
_source.SaveTravels();
return travel.GetViewModel;
}
public TravelViewModel? Delete(TravelBindingModel model)
{
var element = _source.Travels.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Travels.Remove(element);
_source.SaveTravels();
return element.GetViewModel;
}
return null;
}
}
}