using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewelryStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JewelryStoreFileImplement.Implements
{
    public class JewelStorage : IJewelStorage // TODO Lab_2
    {
        private readonly DataFileSingleton _source;
        public JewelStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }
        public List<JewelViewModel> GetFullList()
        {
            return _source.Jewels.Select(x => x.GetViewModel).ToList();
        }
        public List<JewelViewModel> GetFilteredList(JewelSearchModel
       model)
        {
            if (string.IsNullOrEmpty(model.JewelName))
            {
                return new();
            }
            return _source.Jewels
            .Where(x => x.JewelName.Contains(model.JewelName))
           .Select(x => x.GetViewModel)
           .ToList();

        }
        public JewelViewModel? GetElement(JewelSearchModel model)
        {
            if (string.IsNullOrEmpty(model.JewelName) && !model.Id.HasValue)
            {
                return null;
            }
            return _source.Jewels
            .FirstOrDefault(x =>
           (!string.IsNullOrEmpty(model.JewelName) && x.JewelName == model.JewelName) ||
            (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }
        public JewelViewModel? Insert(JewelBindingModel model)
        {
            model.Id = _source.Jewels.Count > 0 ? _source.Jewels.Max(x => x.Id) + 1 : 1;
            var newJewel = Jewel.Create(model);
            if (newJewel == null)
            {
                return null;
            }
            _source.Jewels.Add(newJewel);
            _source.SaveJewels();
            return newJewel.GetViewModel;
        }

        public JewelViewModel? Update(JewelBindingModel model)
        {
            var component = _source.Jewels.FirstOrDefault(x => x.Id == model.Id);
            if (component == null)
            {
                return null;
            }
            component.Update(model);
            _source.SaveJewels();
            return component.GetViewModel;


        }
        public JewelViewModel? Delete(JewelBindingModel model)
        {
            var element = _source.Jewels.FirstOrDefault(x => x.Id == model.Id);
            if (element != null)
            {
                _source.Jewels.Remove(element);
                _source.SaveJewels();
                return element.GetViewModel;
            }
            return null;

        }
    }
}
