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 OperatorStorage : IOperatorStorage
    {
        public List<OperatorViewModel> GetFullList()
        {
            using var context = new TravelCompanyDatabase();
            return context.Operators
            .Select(x => x.GetViewModel)
           .ToList();
        }
        public List<OperatorViewModel> GetFilteredList(OperatorSearchModel
       model)
        {
            if (string.IsNullOrEmpty(model.Login))
            {
                return new();
            }
            using var context = new TravelCompanyDatabase();
            return context.Operators
            .Where(x => x.Login.Contains(model.Login))
           .Select(x => x.GetViewModel)
           .ToList();
        }
        public OperatorViewModel? GetElement(OperatorSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Login) && !model.Id.HasValue)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            return context.Operators
            .FirstOrDefault(x =>
           !string.IsNullOrEmpty(model.Login) && x.Login ==
           model.Login ||
            model.Id.HasValue && x.Id == model.Id)
            ?.GetViewModel;
        }
        public OperatorViewModel? Insert(OperatorBindingModel model)
        {
            var newOperator = Operator.Create(model);
            if (newOperator == null)
            {
                return null;
            }
            using var context = new TravelCompanyDatabase();
            context.Operators.Add(newOperator);
            context.SaveChanges();
            return newOperator.GetViewModel;
        }
        public OperatorViewModel? Update(OperatorBindingModel model)
        {
            using var context = new TravelCompanyDatabase();
            var component = context.Operators.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            context.SaveChanges();
            return component.GetViewModel;
        }
    }
}