using Common.Model;

namespace Common.Database
{
    // This class only supports Products.
    public class InMemoryDatabase : IDatabase
    {
        private int lastID = 0;
        private List<Product> Products { get; set; }

        public InMemoryDatabase()
        {
            Products = new List<Product>();
        }

        public void Delete<T>(int id) where T : Base
        {
            if (typeof(T) == typeof(Product))
            {
                Products.Remove(SearchByID(id));
            }

            throw new NotImplementedException();  
        }

        public void Update<T>(T entity) where T : Base
        {
            if (typeof(T) == typeof(Product))
            {
                var product = entity as Product;
                var storedProduct = SearchByID(product.ID);

                storedProduct.Name = product.Name;
                storedProduct.Description = product.Description;
                storedProduct.Price = product.Price;
                storedProduct.PackagingDate = product.PackagingDate;
                storedProduct.ExpirationDate = product.ExpirationDate;
                storedProduct.Image = product.Image;
            }

            throw new NotImplementedException();
        }

        public IEnumerable<T> List<T>() where T : Base
        {
            if (typeof(T) == typeof(Product))
            {
                return (IEnumerable<T>)Products;
            }

            throw new NotImplementedException();
        }

        public void Store(Product product)
        {
            if (product.ID != 0)
                throw new Exception("Something went wrong: The given product is already in the database");

            product.ID = lastID++;
            Products.Add(product);
        }

        private Product SearchByID(int productID)
        {
            var storedProduct = Products.Where(x => x.ID == productID).SingleOrDefault();

            if (storedProduct == null)
                throw new KeyNotFoundException($"Product with ID = {productID} is not found");

            return storedProduct;
        }       
    }
}
