using Microsoft.IdentityModel.Tokens;
using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemDatabaseImplement.Models;

namespace SecuritySystemDatabaseImplement.Implements
{
    public class ImplementerStorage : IImplementerStorage
    {
        public ImplementerViewModel? Delete(ImplementerBindingModel model)
        {
            using var context = new SecuritySystemDatabase();
            var element = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
            if (element != null)
            {
                context.Implementers.Remove(element);
                context.SaveChanges();
                return element.GetViewModel;
            }
            return null;
        }

        public ImplementerViewModel? GetElement(ImplementerSearchModel model)
        {
            return GetFilteredList(model).FirstOrDefault();
        }

        public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
        {
            var implementers = GetFullList();
            if (model.Id.HasValue)
            {
                implementers = implementers.Where(x => x.Id == model.Id.Value).ToList();
            }
            if (!model.Password.IsNullOrEmpty())
            {
                implementers = implementers.Where(x => x.Password == model.Password).ToList();
            }
            if (!model.ImplementerFIO.IsNullOrEmpty())
            {
                implementers = implementers.Where(x => x.ImplementerFIO == model.ImplementerFIO).ToList();
            }
            return implementers;
        }

        public List<ImplementerViewModel> GetFullList()
        {
            using var context = new SecuritySystemDatabase();
            return context.Implementers.Select(x => x.GetViewModel).ToList();
        }

        public ImplementerViewModel? Insert(ImplementerBindingModel model)
        {
            var newImplementer = Implementer.Create(model);
            if (newImplementer == null)
            {
                return null;
            }
            using var context = new SecuritySystemDatabase();
            context.Implementers.Add(newImplementer);
            context.SaveChanges();
            return newImplementer.GetViewModel;
        }

        public ImplementerViewModel? Update(ImplementerBindingModel model)
        {
            using var context = new SecuritySystemDatabase();
            var client = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
            if (client == null)
            {
                return null;
            }
            client.Update(model);
            context.SaveChanges();
            return client.GetViewModel;
        }
    }
}
