using Microsoft.EntityFrameworkCore;
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.SearchModels.TouristSearchModels;
using TravelCompanyContracts.StoragesContracts.OperatorStoragesContracts;
using TravelCompanyContracts.ViewModels.OperatorViewModels;
using TravelCompanyContracts.ViewModels.TouristViewModels;
using TravelCompanyDatabaseImplement.Models.OperatorModels;

namespace TravelCompanyDatabaseImplement.Implements
{
    public class TourStorage : ITourStorage
    {
        public List<TourViewModel> GetFullList()
        {
            using var context = new TravelCompanyDatabase();
            return context.Tours
            .Select(x => x.GetViewModel)
           .ToList();
        }
        public List<TourViewModel> GetFilteredList(TourSearchModel model)
        {
            if (model.Id.HasValue)
            {
                return new();
            }
            using var context = new TravelCompanyDatabase();
            if (model.Id.HasValue)
            {
                return context.Tours
                .Where(x => x.Id == model.Id)
                .Select(x => x.GetViewModel)
                .ToList();
            }
            else return new();
        }
        public TourViewModel? GetElement(TourSearchModel model)
        {
            if (string.IsNullOrEmpty(model.TourName) && !model.Id.HasValue)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            return context.Tours
            .FirstOrDefault(x => !string.IsNullOrEmpty(model.TourName)
            && x.TourName == model.TourName || model.Id.HasValue && x.Id == model.Id)
            ?.GetViewModel;
        }
        public TourViewModel? Insert(TourBindingModel model)
        {

            var newComponent = Tour.Create(model);
            if (newComponent == null)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            context.Tours.Add(newComponent);
            context.SaveChanges();
            return newComponent.GetViewModel;
        }
        public TourViewModel? Delete(TourBindingModel model)
        {
            using var context = new TravelCompanyDatabase();
            var element = context.Tours.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Tours.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
