using Contracts.BindingModels;
using Contracts.Converters;
using Contracts.SearchModels;
using Contracts.StorageContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseImplement.Implements
{
	public class SellStorage : ISellStorage
	{
		public SellViewModel? Delete(SellSearchModel model)
		{
            using var context = new Database();
            var element = context.Sells.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Sells.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }

		public SellViewModel? GetElement(SellSearchModel model)
		{
            using var context = new Database();
            return context.Sells
                    .Include(x => x.Products)
                    .ThenInclude(x => x.Product)
                    .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public IEnumerable<SellViewModel> GetFilteredList(SellSearchModel? model)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<SellViewModel> GetFullList(SellSearchModel? model)
		{
            using var context = new Database();
            return context.Sells
                .Include(x => x.Products)
                .ThenInclude(x => x.Product)
                .ToList()
                .Select((Sell sell, int index) => sell.GetViewModel)
                .ToList();
        }

		public SellViewModel? Insert(SellBindingModel model)
		{
			using var context = new Database();
			var sell = Sell.Create(context, model);
			if (sell == null)
			{
                return null;
            }
			context.Sells.Add(sell);
			context.SaveChanges();
			return sell.GetViewModel;
		}

		public SellViewModel? Update(SellBindingModel model)
		{
            using var context = new Database();
            using var transaction = context.Database.BeginTransaction();
            try
            {
                var sell = context.Sells.FirstOrDefault(rec => rec.Id == model.Id);
                if (sell == null)
                {
                    return null;
                }
				sell.Update(model);
				context.SaveChanges();
                transaction.Commit();
                return sell.GetViewModel;
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
        }
	}
}
