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

namespace SecureShopFileImplement.Implements
{
    public class FacilitiesStorage : IFacilitiesStorage
    {
        private readonly DataFileSingleton _source;

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

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

        public List<FacilitiesViewModel> GetFilteredList(FacilitiesSearchModel model)
        {
            if (string.IsNullOrEmpty(model.FacilitiesName))
            {
                return new();
            }
            return _source.Facilitiess.Where(x => x.FacilitiesName.Contains(model.FacilitiesName)).Select(x => x.GetViewModel).ToList();
        }

        public FacilitiesViewModel? GetElement(FacilitiesSearchModel model)
        {
            if (string.IsNullOrEmpty(model.FacilitiesName) && !model.Id.HasValue)
            {
                return null;
            }
            return _source.Facilitiess.FirstOrDefault(x => (!string.IsNullOrEmpty(model.FacilitiesName) && x.FacilitiesName == model.FacilitiesName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public FacilitiesViewModel? Insert(FacilitiesBindingModel model)
        {
            model.Id = _source.Facilitiess.Count > 0 ? _source.Facilitiess.Max(x => x.Id) + 1 : 1;
            var newFacilities = Facilities.Create(model);
            if (newFacilities == null)
            {
                return null;
            }
            _source.Facilitiess.Add(newFacilities);
            _source.SaveFacilitiess();
            return newFacilities.GetViewModel;
        }

        public FacilitiesViewModel? Update(FacilitiesBindingModel model)
        {
            var Facilities = _source.Facilitiess.FirstOrDefault(x => x.Id == model.Id);
            if (Facilities == null)
            {
                return null;
            }
            Facilities.Update(model);
            _source.SaveFacilitiess();
            return Facilities.GetViewModel;
        }

        public FacilitiesViewModel? Delete(FacilitiesBindingModel model)
        {
            var element = _source.Facilitiess.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                _source.Facilitiess.Remove(element);
                _source.SaveFacilitiess();
                return element.GetViewModel;
            }
            return null;
        }
    }
}