using DinerContracts.BindingModels;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerFileImplement.Models;

namespace DinerFileImplement.Implements
{
    public class SnackStorage : ISnackStorage
    {
        private readonly DataFileSingleton source;
        public SnackStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public SnackViewModel? Delete(SnackBindingModel model)
        {
            var element = source.Snacks.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                source.Snacks.Remove(element);
                source.SaveSnacks();
                return element.GetViewModel;
            }
            return null;
        }

        public SnackViewModel? GetElement(SnackSearchModel model)
        {
            if (string.IsNullOrEmpty(model.SnackName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Snacks
                .FirstOrDefault(x => (!string.IsNullOrEmpty(model.SnackName) && x.SnackName == model.SnackName) ||
                   (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public List<SnackViewModel> GetFilteredList(SnackSearchModel model)
        {
            if (string.IsNullOrEmpty(model.SnackName))
            {
                return new();
            }
            return source.Snacks
                .Where(x => x.SnackName.Contains(model.SnackName))
                .Select(x => x.GetViewModel)
                .ToList();
        }

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

        public SnackViewModel? Insert(SnackBindingModel model)
        {
            model.Id = source.Snacks.Count > 0 ? source.Snacks.Max(x => x.Id) + 1 : 1;
            var newSnack = Snack.Create(model);
            if (newSnack == null)
            {
                return null;
            }
            source.Snacks.Add(newSnack);
            source.SaveSnacks();
            return newSnack.GetViewModel;
        }

        public SnackViewModel? Update(SnackBindingModel model)
        {
            var element = source.Snacks.FirstOrDefault(x => x.Id == model.Id);
            if (element == null)
            {
                return null;
            }

            element.Update(model);
            source.SaveSnacks();

            return element.GetViewModel;
        }
    }
}
