using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZooContracts.StoragesContracts;
using ZooContracts.BindingModels;
using ZooContracts.SearchModel;
using ZooContracts.StoragesContracts;
using ZooContracts.ViewModels;
using ZooDatabaseImplements;
using ZooDatabaseImplements.Models;

namespace ZooDatabaseImplements.Implements
{
    public class CostStorage : ICostStorage
    {
        public CostViewModel? Delete(CostBindingModel model)
        {
            using var context = new ZooDatabase();
            var element = context.Costs.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                context.Costs.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }

        public CostViewModel GetElement(CostSearchModel model)
        {
            using var context = new ZooDatabase();
            if (model.Id.HasValue)//сначала ищем по Id
            {
                return context.Costs
                    .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
            }
            if (!string.IsNullOrEmpty(model.CostName))//затем по названию
            {
                return context.Costs
                    .FirstOrDefault(x => x.CostName == model.CostName)?.GetViewModel;
            }
            return null;
        }

        public List<CostViewModel> GetFilteredList(CostSearchModel model)
        {
            using var context = new ZooDatabase();
            return context.Costs
                .Where(x => x.Id == model.Id)
                .Select(x => x.GetViewModel)
                .ToList();
        }

        public List<CostViewModel> GetFullList()
        {
            using var context = new ZooDatabase();
            return context.Costs
                .Select(x => x.GetViewModel)
                .ToList();
        }

        public CostViewModel? Insert(CostBindingModel model)
        {
            using var context = new ZooDatabase();
            var newCost = Cost.Create(model);
            if (newCost == null)
            {
                return null;
            }
            context.Costs.Add(newCost);
            context.SaveChanges();
            return newCost.GetViewModel;
        }

        public CostViewModel? Update(CostBindingModel model)
        {
            using var context = new ZooDatabase();
            var Cost = context.Costs.FirstOrDefault(x => x.Id == model.Id);
            if (Cost == null)
            {
                return null;
            }
            Cost.Update(model);
            context.SaveChanges();
            return Cost.GetViewModel;
        }
    }
}
