using BarContracts.BindingModels;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarFileImplement.Models;

namespace BarFileImplement.Implements
{
    public class CocktailStorage : ICocktailStorage
    {
        private readonly DataFileSingleton _source;

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

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

        public List<CocktailViewModel> GetFilteredList(CocktailSearchModel Model)
        {
            if (string.IsNullOrEmpty(Model.CocktailName))
                return new();

            return _source.Cocktails.Where(x => x.CocktailName.Contains(Model.CocktailName)).Select(x => x.GetViewModel).ToList();
        }

        public CocktailViewModel? GetElement(CocktailSearchModel Model)
        {
            if (string.IsNullOrEmpty(Model.CocktailName) && !Model.Id.HasValue)
                return null;

            return _source.Cocktails.FirstOrDefault(x => (!string.IsNullOrEmpty(Model.CocktailName) && x.CocktailName == Model.CocktailName) || (Model.Id.HasValue && x.Id == Model.Id))?.GetViewModel;
        }

        public CocktailViewModel? Insert(CocktailBindingModel Model)
        {
            Model.Id = _source.Cocktails.Count > 0 ? _source.Cocktails.Max(x => x.Id) + 1 : 1;

            var NewCocktail = Cocktail.Create(Model);

            if (NewCocktail == null)
                return null;

            _source.Cocktails.Add(NewCocktail);
            _source.SaveCocktails();

            return NewCocktail.GetViewModel;
        }

        public CocktailViewModel? Update(CocktailBindingModel Model)
        {
            var Cocktail = _source.Cocktails.FirstOrDefault(x => x.Id == Model.Id);

            if (Cocktail == null)
                return null;

            Cocktail.Update(Model);
            _source.SaveCocktails();

            return Cocktail.GetViewModel;
        }

        public CocktailViewModel? Delete(CocktailBindingModel Model)
        {
            var Cocktail = _source.Cocktails.FirstOrDefault(x => x.Id == Model.Id);

            if (Cocktail == null)
                return null;

            _source.Cocktails.Remove(Cocktail);
            _source.SaveCocktails();

            return Cocktail.GetViewModel;
        }
    }
}
