using DressAtelierContracts.BindingModels;
using DressAtelierContracts.SearchModels;
using DressAtelierContracts.StorageContracts;
using DressAtelierContracts.ViewModels;
using DressAtelierDatabaseImplement.Models;
using DressAtelierDatabaseImplementation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DressAtelierDatabaseImplement.Implements
{
    public class ClientStorage : IClientStorage
    {
        public ClientViewModel? Insert(ClientBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var newClient = Client.Create(model); 
            if(newClient == null) { return null; }
            context.Clients.Add(newClient);
            context.SaveChanges();
            return newClient.GetViewModel;
        }

        public ClientViewModel? Update(ClientBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var client = context.Clients.FirstOrDefault(x => x.ID == model.ID);
            if(client == null) { return null; };
            client.Update(model);
            context.SaveChanges();
            return client.GetViewModel;
        }

        public ClientViewModel? Delete(ClientBindingModel model)
        {
            using var context = new DressAtelierDatabase();
            var client = context.Clients.FirstOrDefault(x => x.ID == model.ID);
            if(client == null) { return null;}
            context.Clients.Remove(client);
            context.SaveChanges();
            return client.GetViewModel;
        }

        public ClientViewModel? GetElement(ClientSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Email) && !model.ID.HasValue) { return null; }
            using var context = new DressAtelierDatabase();
            return context.Clients.FirstOrDefault(x => (!(string.IsNullOrEmpty(model.Email)) && model.Email == x.Email) || (model.ID.HasValue && model.ID == x.ID))?.GetViewModel;
        }

        public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
        {
            if (string.IsNullOrEmpty(model.Email)) { return new(); }
            using var context = new DressAtelierDatabase();
            return context.Clients.Where(x => x.Email.Equals(model.Email)).Select(x => x.GetViewModel).ToList();
        }

        public List<ClientViewModel> GetFullList()
        {
            using var context = new DressAtelierDatabase();
            return context.Clients.Select(x => x.GetViewModel).ToList();
        }
        
    }
}
