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

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;
			newMachine.UpdateWorkers(context, model);
			context.Machines.Remove(newMachine);
			context.SaveChanges();
			return newMachine.GetViewModel;
		}

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

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

		public List<MachineViewModel> GetFullList()
		{
			using var context = new FactoryGoWorkDatabase();
            return context.Machines.Include(p => p.Workers).ThenInclude(p => p.Worker).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);
			newMachine.UpdateWorkers(context, model);
			context.SaveChanges();
			return newMachine.GetViewModel;
		}
	}
}
