using DatabaseImplement.Models;
using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.ViewModels;
using Contracts.StoragesContracts;

namespace DatabaseImplement.Implements
{
	public class DetailStorage : IDetailStorage
	{
		public DetailViewModel? Delete(DetailBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newDetail = context.Details.FirstOrDefault(x => x.Id == model.Id);
			if (newDetail == null)
				return null;
			context.Details.Remove(newDetail);
			context.SaveChanges();
			return newDetail.GetViewModel;
		}

		public DetailViewModel? GetElement(DetailSearchModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			return context.Details.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Equals(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
		}

		public List<DetailViewModel> GetFilteredList(DetailSearchModel model)
		{
			if (!model.UserId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue)
			{
				return new();
			}
			using var context = new FactoryGoWorkDatabase();
			if (model.DateFrom.HasValue)
				return context.Details.Where(x => x.UserId == model.UserId).Where(x => x.DateCreate <= model.DateTo && x.DateCreate >= model.DateFrom).Select(x => x.GetViewModel).ToList();
			else
				return context.Details.Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList();

		}

		public List<DetailViewModel> GetFullList()
		{
			using var context = new FactoryGoWorkDatabase();
			return context.Details.Select(x => x.GetViewModel).ToList();
		}

		public DetailViewModel? Insert(DetailBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newDetail = Detail.Create(model);
			if (newDetail == null)
				return null;
			context.Details.Add(newDetail);
			context.SaveChanges();
			return newDetail.GetViewModel;
		}

		public DetailViewModel? Update(DetailBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newDetail = context.Details.FirstOrDefault(x => x.Id == model.Id);
			if (newDetail == null)
				return null;
			newDetail.Update(model);
			context.SaveChanges();
			return newDetail.GetViewModel;
		}
	}
}
