using FishFactoryContracts.BindingModels;
using FishFactoryContracts.SearchModels;
using FishFactoryContracts.StoragesContracts;
using FishFactoryContracts.ViewModels;
using FishFactoryFileImplement.Models;

namespace FishFactoryFileImplement.Implements
{
    public class CannedStorage : ICannedStorage
    {
        private readonly DataFileSingleton source;
        public CannedStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

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

        public List<CannedViewModel> GetFilteredList(CannedSearchModel model)
        {
            if (string.IsNullOrEmpty(model.CannedName))
            {
                return new();
            }
            return source.ListCanned.Where(x =>
                x.CannedName.Contains(model.CannedName)).Select(x => x.GetViewModel).ToList();
        }

        public CannedViewModel? GetElement(CannedSearchModel model)
        {
            if (string.IsNullOrEmpty(model.CannedName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.ListCanned.FirstOrDefault(x =>
                (!string.IsNullOrEmpty(model.CannedName) && x.CannedName ==
                model.CannedName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public CannedViewModel? Insert(CannedBindingModel model)
        {
            model.Id = source.ListCanned.Count > 0 ? source.ListCanned.Max(x => x.Id) + 1 : 1;
            var newCanned = Canned.Create(model);
            if (newCanned == null)
            {
                return null;
            }
            source.ListCanned.Add(newCanned);
            source.SaveListCanned();
            return newCanned.GetViewModel;
        }

        public CannedViewModel? Update(CannedBindingModel model)
        {
            var canned = source.ListCanned.FirstOrDefault(x => x.Id == model.Id);
            if (canned == null)
            {
                return null;
            }
            canned.Update(model);
            source.SaveListCanned();
            return canned.GetViewModel;
        }

        public CannedViewModel? Delete(CannedBindingModel model)
        {
            var element = source.ListCanned.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                source.ListCanned.Remove(element);
                source.SaveListCanned();
                return element.GetViewModel;
            }
            return null;
        }
    }
}
