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

namespace BarDatabaseImplement.Implements
{
    public class ComponentStorage : IComponentStorage
    {
        public List<ComponentViewModel> GetFullList()
        {
            using var Context = new BarDatabase();
            return Context.Components.Select(x => x.GetViewModel).ToList();
        }

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

            using var Context = new BarDatabase();
            return Context.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;

            using var Context = new BarDatabase();
            return Context.Components
                .FirstOrDefault(x => (!string.IsNullOrEmpty(Model.ComponentName) && x.ComponentName == Model.ComponentName) ||
                (Model.Id.HasValue && x.Id == Model.Id))?.GetViewModel;
        }

        public ComponentViewModel? Insert(ComponentBindingModel Model)
        {
            var NewComponent = Component.Create(Model);

            if (NewComponent == null)
                return null;

            using var Context = new BarDatabase();
            Context.Components.Add(NewComponent);
            Context.SaveChanges();

            return NewComponent.GetViewModel;
        }

        public ComponentViewModel? Update(ComponentBindingModel Model)
        {
            using var Context = new BarDatabase();

            var Component = Context.Components.FirstOrDefault(x => x.Id == Model.Id);

            if (Component == null)
                return null;

            Component.Update(Model);
            Context.SaveChanges();

            return Component.GetViewModel;
        }

        public ComponentViewModel? Delete(ComponentBindingModel Model)
        {
            using var Context = new BarDatabase();
            var Component = Context.Components.FirstOrDefault(rec => rec.Id == Model.Id);

            if (Component == null)
                return null;

            Context.Components.Remove(Component);
            Context.SaveChanges();
            return Component.GetViewModel;
        }
    }
}
