using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;

namespace MotorPlantFileImplement.Implements
{
    public class EngineStorage : IEngineStorage
    {
        private readonly DataFileSingleton source;
        public EngineStorage()
        {
            source = DataFileSingleton.GetInstance();
        }
        public EngineViewModel? GetElement(EngineSearchModel model)
        {
            if (string.IsNullOrEmpty(model.EngineName) && !model.Id.HasValue)
            {
                return null;
            }
            return source.Engines.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EngineName) && x.EngineName == model.EngineName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
        }
        public List<EngineViewModel> GetFilteredList(EngineSearchModel model)
        {
            if (string.IsNullOrEmpty(model.EngineName))
            {
                return new();
            }
            return source.Engines.Where(x => x.EngineName.Contains(model.EngineName)).Select(x => x.GetViewModel).ToList();
        }
        public List<EngineViewModel> GetFullList()
        {
            return source.Engines.Select(x => x.GetViewModel).ToList();
        }
        public EngineViewModel? Insert(EngineBindingModel model)
        {
            model.Id = source.Engines.Count > 0 ? source.Engines.Max(x => x.Id) + 1 : 1;
            var newDoc = Engine.Create(model);
            if (newDoc == null)
            {
                return null;
            }
            source.Engines.Add(newDoc);
            source.SaveEngines();
            return newDoc.GetViewModel;
        }
        public EngineViewModel? Update(EngineBindingModel model)
        {
            var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
            if (document == null)
            {
                return null;
            }
            document.Update(model);
            source.SaveEngines();
            return document.GetViewModel;
        }
        public EngineViewModel? Delete(EngineBindingModel model)
        {
            var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
            if (document == null)
            {
                return null;
            }
            document.Update(model);
            source.SaveEngines();
            return document.GetViewModel;
        }
    }
}
