using IceCreamShopContracts.BindingModels;
using IceCreamShopContracts.SearchModels;
using IceCreamShopContracts.StoragesContracts;
using IceCreamShopContracts.ViewModels;
using IceCreamShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace IceCreamShopFileImplement.Implements
{
    public class IceCreamStorage : IIceCreamStorage
    {
        private readonly DataFileSingleton source;

        public IceCreamStorage()
        {
            source = DataFileSingleton.GetInstance();
        }

        public IceCreamViewModel? GetElement(IceCreamSearchModel model)
        {
            if (string.IsNullOrEmpty(model.IceCreamName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.IceCreams.FirstOrDefault(x => (!string.IsNullOrEmpty(model.IceCreamName) && x.IceCreamName == model.IceCreamName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }

        public List<IceCreamViewModel> GetFilteredList(IceCreamSearchModel model)
        {
            if (string.IsNullOrEmpty(model.IceCreamName))
            {
                return new();
            }
            return source.IceCreams.Where(x => x.IceCreamName.Contains(model.IceCreamName)).Select(x => x.GetViewModel).ToList();
        }

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

        public IceCreamViewModel? Insert(IceCreamBindingModel model)
        {
            model.Id = source.IceCreams.Count > 0 ? source.IceCreams.Max(x => x.Id) + 1 : 1;
            var newDoc = IceCream.Create(model);
            if (newDoc == null)
            {
                return null;
            }
            source.IceCreams.Add(newDoc);
            source.SaveIceCreams();
            return newDoc.GetViewModel;
        }

        public IceCreamViewModel? Update(IceCreamBindingModel model)
        {
            var document = source.IceCreams.FirstOrDefault(x => x.Id == model.Id);
            if (document == null)
            {
                return null;
            }
            document.Update(model);
            source.SaveIceCreams();
            return document.GetViewModel;
        }
        public IceCreamViewModel? Delete(IceCreamBindingModel model)
        {
            var document = source.IceCreams.FirstOrDefault(x => x.Id == model.Id);
            if (document == null)
            {
                return null;
            }
            document.Update(model);
            source.SaveIceCreams();
            return document.GetViewModel;
        }
    }
}
