using BarContracts.BindingModels;
using BarContracts.SearchModels;
using BarContracts.StoragesContracts;
using BarContracts.ViewModels;
using BarFileImplement.Models;

namespace BarFileImplement.Implements
{
    public class ComponentStorage : IComponentStorage
    {
        private readonly DataFileSingleton _source;

        public ComponentStorage()
        {
            _source = DataFileSingleton.GetInstance();
        }

        public List<ComponentViewModel> GetFullList()
        {
            return _source.Components.Select(x => x.GetViewModel).ToList();
        }

        public List<ComponentViewModel> GetFilteredList(ComponentSearchModel Model)
        {
            if (string.IsNullOrEmpty(Model.ComponentName))
                return new();

            return _source.Components.Where(x => x.ComponentName.Contains(Model.ComponentName)).Select(x => x.GetViewModel).ToList();
        }

        public ComponentViewModel? GetElement(ComponentSearchModel Model)
        {
            if (string.IsNullOrEmpty(Model.ComponentName) && !Model.Id.HasValue)
                return null;

            return _source.Components.FirstOrDefault(x =>
                (!string.IsNullOrEmpty(Model.ComponentName) && x.ComponentName == Model.ComponentName) ||
                (Model.Id.HasValue && x.Id == Model.Id))?.GetViewModel;
        }

        public ComponentViewModel? Insert(ComponentBindingModel Model)
        {
            Model.Id = _source.Components.Count > 0 ? _source.Components.Max(x => x.Id) + 1 : 1;

            var NewComponent = Component.Create(Model);

            if (NewComponent == null)
                return null;

            _source.Components.Add(NewComponent);
            _source.SaveComponents();

            return NewComponent.GetViewModel;
        }

        public ComponentViewModel? Update(ComponentBindingModel Model)
        {
            var Component = _source.Components.FirstOrDefault(x => x.Id == Model.Id);

            if (Component == null)
                return null;

            Component.Update(Model);
            _source.SaveComponents();

            return Component.GetViewModel;
        }

        public ComponentViewModel? Delete(ComponentBindingModel Model)
        {
            var Component = _source.Components.FirstOrDefault(x => x.Id == Model.Id);

            if (Component == null)
                return null;

            _source.Components.Remove(Component);
            _source.SaveComponents();

            return Component.GetViewModel;
        }
    }
}
