using Common.Model;
using Microsoft.EntityFrameworkCore;

namespace Common.Database
{
    public class SQLiteDatabase : IDatabase, IDisposable
    {
        private ApiaryContext context;

        public SQLiteDatabase()
        {
            context = new ApiaryContext();
            context.Database.EnsureCreated();
        }

        public void Dispose()
        {
            context?.Dispose();
        }

        public void Store(Product product)
        {
            context.Products.Add(product);
            context.SaveChanges();
        }

        public void Delete<T>(int id) where T : Base
        {
            DbSet<T> binding = GetBinding<T>();
            
            T? entity = binding.Where(x => x.ID == id).FirstOrDefault();

            if (entity == null)
                throw new KeyNotFoundException($"Item with ID = {id} is not found");

            binding.Remove(entity);
            context.SaveChanges();
        }

        public void Update<T>(T entity) where T : Base
        {
            DbSet<T> binding = GetBinding<T>();

            binding.Update(entity);
            context.SaveChanges();
        }

        public IEnumerable<T> List<T>() where T : Base
        {
            DbSet<T> binding = GetBinding<T>();
            return binding.ToList();
        }

        private DbSet<T> GetBinding<T>() where T : Base
        {
            if (typeof(T) == typeof(Product))
                return context.Products as DbSet<T>;
            else if (typeof(T) == typeof(Order))
                return context.Orders as DbSet<T>;
            else
                throw new NotImplementedException();
        }
    }
}
