using FishFactoryContracts.BindingModels;
using FishFactoryContracts.SearchModels;
using FishFactoryContracts.StoragesContracts;
using FishFactoryContracts.ViewModels;
using FishFactoryFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FishFactoryFileImplement.Implements
{
    public class CannedStorage : ICannedStorage
    {
        private readonly DataFileSingleton source;
        public CannedStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public List<CannedViewModel> GetFullList()
        {
            return source.Canneds.Select(x => x.GetViewModel).ToList();
        }
        public List<CannedViewModel> GetFilteredList(CannedSearchModel model)
        {
            return source.Canneds.Where(x => x.Id == model.Id)
                .Select(x => x.GetViewModel)
                .ToList();
        }
        public CannedViewModel? GetElement(CannedSearchModel model)
        {
            if (!model.Id.HasValue)
            {
                return null;
            }
            return source.Canneds.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.Canneds.Count > 0 ? source.Canneds.Max(x => x.Id) + 1 : 1;
            var newCanned = Canned.Create(model);
            if (newCanned == null)
            {
                return null;
            }
            source.Canneds.Add(newCanned);
            source.SaveCannedes();
            return newCanned.GetViewModel;
        }
        public CannedViewModel? Update(CannedBindingModel model)
        {
            var component = source.Canneds.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            source.SaveCannedes();
            return component.GetViewModel;
        }
        public CannedViewModel? Delete(CannedBindingModel model)
        {
            var component = source.Canneds.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            source.Canneds.Remove(component);
            source.SaveCannedes();
            return component.GetViewModel;
        }
    }
}
