using SecuritySystemContracts.BindingModels;
using SecuritySystemContracts.SearchModels;
using SecuritySystemContracts.StoragesContracts;
using SecuritySystemContracts.ViewModels;
using SecuritySystemFileImplement.Models;

namespace SecuritySystemFileImplement.Implements
{
    public class ImplementerStorage : IImplementerStorage
    {
        private readonly DataFileSingleton source;

        public ImplementerStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

        public List<ImplementerViewModel> GetFullList()
        {
            return source.Implementers.Select(x => x.GetViewModel).ToList();
        }

        public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
        {
            var clients = source.Implementers
            .Select(x => x.GetViewModel)
            .ToList();
            if (model.Id.HasValue)
            {
                clients = clients.Where(x => x.Id == model.Id.Value).ToList();
            }
            if (model.Password != null)
            {
                clients = clients.Where(x => x.Password == model.Password).ToList();
            }
            if (model.ImplementerFIO != null)
            {
                clients = clients.Where(x => x.ImplementerFIO == model.ImplementerFIO).ToList();
            }
            return clients;
        }

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

        public ImplementerViewModel? Insert(ImplementerBindingModel model)
        {
            model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1;
            var newImplementer = Implementer.Create(model);
            if (newImplementer == null)
            {
                return null;
            }
            source.Implementers.Add(newImplementer);
            source.SaveImplementers();
            return newImplementer.GetViewModel;
        }

        public ImplementerViewModel? Update(ImplementerBindingModel model)
        {
            var client = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
            if (client == null)
            {
                return null;
            }
            client.Update(model);
            source.SaveImplementers();
            return client.GetViewModel;
        }

        public ImplementerViewModel? Delete(ImplementerBindingModel model)
        {
            var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                source.Implementers.Remove(element);
                source.SaveImplementers();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
