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
    {
        private readonly DataFileSingleton source;

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

        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 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 List<JewelViewModel> GetFullList()
        {
            return source.Jewels.Select(x => x.GetViewModel).ToList();
        }

        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 jewel = source.Jewels.FirstOrDefault(x => x.Id == model.Id);
            if (jewel == null)
            {
                return null;
            }
            jewel.Update(model);
            source.SaveJewels();
            return jewel.GetViewModel;
        }

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