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

namespace DatabaseImplement.Implements
{
	public class ImplementerStorage : IImplementerStorage
	{
		public ImplementerViewModel? Delete(ImplementerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newImplementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
			if (newImplementer == null)
				return null;
			context.Implementers.Remove(newImplementer);
			context.SaveChanges();
			return newImplementer.GetViewModel;
		}

		public ImplementerViewModel? GetElement(ImplementerSearchModel model)
		{
			if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login)) { return null; }
			using var context = new FactoryGoWorkDatabase();
			return context.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && x.Login.Equals(model.Login) && x.Password.Equals(model.Password)))?.GetViewModel; ;
		}

		public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
		{
			if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login))
				return new();
			using var context = new FactoryGoWorkDatabase();
			if (model.Id.HasValue)
			{
				return context.Implementers.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
			}
			else
			{
				return context.Implementers.Where(x => x.Login.Equals(model.Login)).Select(x => x.GetViewModel).ToList();
			}
		}

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

		public ImplementerViewModel? Insert(ImplementerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newImplementer = Implementer.Create(model);
			if (newImplementer == null)
				return null;
			context.Implementers.Add(newImplementer);
			context.SaveChanges();
			return newImplementer.GetViewModel;
		}

		public ImplementerViewModel? Update(ImplementerBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newImplementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
			if (newImplementer == null)
				return null;
			newImplementer.Update(model);
			context.SaveChanges();
			return newImplementer.GetViewModel;
		}
	}
}
