using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels.OperatorBindingModels;
using TravelCompanyContracts.SearchModels.OperatorSearchModels;
using TravelCompanyContracts.StoragesContracts.OperatorStoragesContracts;
using TravelCompanyContracts.ViewModels.OperatorViewModels;
using TravelCompanyDatabaseImplement.Models.OperatorModels;

namespace TravelCompanyDatabaseImplement.Implements
{
    public class GuideStorage : IGuideStorage
    {
        public List<GuideViewModel> GetFullList()
        {
            using var context = new TravelCompanyDatabase();
            return context.Guides
            .Select(x => x.GetViewModel)
           .ToList();
        }
        public List<GuideViewModel> GetFilteredList(GuideSearchModel model)
        {
          
            using var context = new TravelCompanyDatabase();
            return context.Guides
           .Select(x => x.GetViewModel)
           .ToList();
        }
        public GuideViewModel? GetElement(GuideSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Surname) && !model.Id.HasValue)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            return context.Guides
            .FirstOrDefault(x => !string.IsNullOrEmpty(model.Surname)
            && x.Surname == model.Surname || model.Id.HasValue && x.Id == model.Id)
            ?.GetViewModel;
        }
        public GuideViewModel? Insert(GuideBindingModel model)
        {

            var newComponent = Guide.Create(model);
            if (newComponent == null)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            context.Guides.Add(newComponent);
            context.SaveChanges();
            return newComponent.GetViewModel;
        }
        public GuideViewModel? Delete(GuideBindingModel model)
        {
            using var context = new TravelCompanyDatabase();
            var element = context.Guides.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Guides.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
