using AbstractFoodOrdersContracts.BindingModels;
using AbstractFoodOrdersContracts.SearchModels;
using AbstractFoodOrdersContracts.StoragesContracts;
using AbstractFoodOrdersContracts.ViewModels;
using AbstractFoodOrdersFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AbstractFoodOrdersFileImplement.Implements
{
    public class DishStorage : IDishStorage
    {
        private readonly DataFileSingleton source;
        public DishStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public DishViewModel? Delete(DishBindingModel model)
        {
            var element = source.Dishes.FirstOrDefault(x => x.Id ==
           model.Id);
            if (element != null)
            {
                source.Dishes.Remove(element);
                source.SaveDishes();
                return element.GetViewModel;
            }
            return null;
        }

        public DishViewModel? GetElement(DishSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DishName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Dishes.FirstOrDefault(x =>(!string.IsNullOrEmpty(model.DishName) && x.DishName ==model.DishName) ||
            (model.Id.HasValue && x.Id == model.Id))
            ?.GetViewModel;
        }

        public List<DishViewModel> GetFilteredList(DishSearchModel model)
        {
            if (string.IsNullOrEmpty(model.DishName))
            {
                return new();
            }
            return source.Dishes.Where(x => x.DishName.Contains(model.DishName)).Select(x => x.GetViewModel).ToList();
        }

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

        public DishViewModel? Insert(DishBindingModel model)
        {
            model.Id = source.Dishes.Count > 0 ? source.Dishes.Max(x =>
           x.Id) + 1 : 1;
            var newComponent = Dish.Create(model);
            if (newComponent == null)
            {
                return null;
            }
            source.Dishes.Add(newComponent);
            source.SaveDishes();
            return newComponent.GetViewModel;
        }

        public DishViewModel? Update(DishBindingModel model)
        {
            var component = source.Dishes.FirstOrDefault(x => x.Id ==
           model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            source.SaveDishes();
            return component.GetViewModel;
        }
    }
}
