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

namespace DatabaseImplement.Implements
{
	public class MachineStorage : IMachineStorage
	{
		public MachineViewModel? Delete(MachineBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newMachine = context.Machines.FirstOrDefault(x => x.Id == model.Id);
			if (newMachine == null)
				return null;
			context.Machines.Remove(newMachine);
			context.SaveChanges();
			return newMachine.GetViewModel;
		}

		public MachineViewModel? GetElement(MachineSearchModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			return context.Machines.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Title) && x.Title.Contains(model.Title)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
		}

		public List<MachineViewModel> GetFilteredList(MachineSearchModel model)
		{
			if (!model.Id.HasValue && string.IsNullOrEmpty(model.Title) && !model.UserId.HasValue)
			{
				return new();
			}
			using var context = new FactoryGoWorkDatabase();
			if (model.Id.HasValue)
			{
				return context.Machines.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
			}
			else if (model.UserId.HasValue)
			{
				return context.Machines.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList();
			}
			else
			{
				return context.Machines.Where(x => model.Title == x.Title).Select(x => x.GetViewModel).ToList();
			}
		}

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

		public MachineViewModel? Insert(MachineBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newMachine = Machine.Create(model, context);
			if (newMachine == null)
				return null;
			context.Machines.Add(newMachine);
			context.SaveChanges();
			return newMachine.GetViewModel;
		}

		public MachineViewModel? Update(MachineBindingModel model)
		{
			using var context = new FactoryGoWorkDatabase();
			var newMachine = context.Machines.FirstOrDefault(x => x.Id == model.Id);
			if (newMachine == null)
				return null;
			newMachine.Update(model);
			context.SaveChanges();
			return newMachine.GetViewModel;
		}
	}
}