using SecureShopContracts.BindingModels;
using SecureShopContracts.SearchModels;
using SecureShopContracts.StoragesContracts;
using SecureShopContracts.ViewModels;
using SecureShopFileImplement.Models;

namespace SecureShopFileImplement.Implements
{
    public class SecureStorage : ISecureStorage
    {
        private readonly DataFileSingleton _source;

        public SecureStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }

        public List<SecureViewModel> GetFullList()
        {
            return _source.Secures.Select(x => x.GetViewModel).ToList();
        }

        public List<SecureViewModel> GetFilteredList(SecureSearchModel model)
        {
            if (string.IsNullOrEmpty(model.SecureName))
            {
                return new();
            }
            return _source.Secures.Where(x => x.SecureName.Contains(model.SecureName)).Select(x => x.GetViewModel).ToList();
        }

        public SecureViewModel? GetElement(SecureSearchModel model)
        {
            if (string.IsNullOrEmpty(model.SecureName) && !model.Id.HasValue)
            {
                return null;
            }
            return _source.Secures.FirstOrDefault(x => (!string.IsNullOrEmpty(model.SecureName) && x.SecureName == model.SecureName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public SecureViewModel? Insert(SecureBindingModel model)
        {
            model.Id = _source.Secures.Count > 0 ? _source.Secures.Max(x => x.Id) + 1 : 1;
            var newSecure = Secure.Create(model);
            if (newSecure == null)
            {
                return null;
            }
            _source.Secures.Add(newSecure);
            _source.SaveSecures();
            return newSecure.GetViewModel;
        }

        public SecureViewModel? Update(SecureBindingModel model)
        {
            var Secure = _source.Secures.FirstOrDefault(x => x.Id == model.Id);
            if (Secure == null)
            {
                return null;
            }
            Secure.Update(model);
            _source.SaveSecures();
            return Secure.GetViewModel;
        }

        public SecureViewModel? Delete(SecureBindingModel model)
        {
            var element = _source.Secures.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                _source.Secures.Remove(element);
                _source.SaveSecures();
                return element.GetViewModel;
            }
            return null;
        }
    }
}