using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TravelCompanyContracts.BindingModels.TouristBindingModels;
using TravelCompanyContracts.SearchModels.TouristSearchModels;
using TravelCompanyContracts.StoragesContracts.TouristStoragesContracts;
using TravelCompanyContracts.ViewModels.TouristViewModels;
using TravelCompanyDatabaseImplement.Models.TouristModel;

namespace TravelCompanyDatabaseImplement.Implements
{
    public class TouristStorage : ITouristStorage
    {
        public List<TouristViewModel> GetFullList()
        {
            using var context = new TravelCompanyDatabase();
            return context.Tourists
            .Select(x => x.GetViewModel)
           .ToList();
        }
        public List<TouristViewModel> GetFilteredList(TouristSearchModel
       model)
        {
            if (string.IsNullOrEmpty(model.Login))
            {
                return new();
            }
            using var context = new TravelCompanyDatabase();
            return context.Tourists
            .Where(x => x.Login.Contains(model.Login))
           .Select(x => x.GetViewModel)
           .ToList();
        }
        public TouristViewModel? GetElement(TouristSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            return context.Tourists
            .FirstOrDefault(x =>
           (!string.IsNullOrEmpty(model.Login) && x.Login ==
           model.Login) ||
            (model.Id.HasValue && x.Id == model.Id))
            ?.GetViewModel;
        }
        public TouristViewModel? Insert(TouristBindingModel model)
        {
            var newTourist = Tourist.Create(model);
            if (newTourist == null)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            context.Tourists.Add(newTourist);
            context.SaveChanges();
            return newTourist.GetViewModel;
        }
        public TouristViewModel? Update(TouristBindingModel model)
        {
            using var context = new TravelCompanyDatabase();
            var component = context.Tourists.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            context.SaveChanges();
            return component.GetViewModel;
        }
    }
}
