using System;
using System.Collections.Generic;
using System.Linq;
namespace ExpiryTracker
{
public class ProductRepository
{
private static List<Product> products = new List<Product>();
private static int nextId = 1;
public void Add(Product product)
{
product.Id = nextId;
nextId++;
products.Add(product);
}
public void Update(Product product)
{
Product existingProduct = products.FirstOrDefault(p => p.Id == product.Id);
if (existingProduct != null)
{
existingProduct.ProductName = product.ProductName;
existingProduct.ProductionDate = product.ProductionDate;
existingProduct.ExpiryDate = product.ExpiryDate;
existingProduct.Quantity = product.Quantity;
}
}
public void Delete(int id)
{
Product product = products.FirstOrDefault(p => p.Id == id);
if (product != null)
{
products.Remove(product);
}
}
public List<Product> GetAll()
{
return products
.OrderBy(p => p.ExpiryDate)
.ToList();
}
public List<Product> GetExpired()
{
return products
.Where(p => p.ExpiryDate.Date < DateTime.Today)
.OrderBy(p => p.ExpiryDate)
.ToList();
}
public List<Product> GetFiltered(string name, DateTime? dateFrom, DateTime? dateTo, bool onlyExpired)
{
IEnumerable<Product> result = products;
if (!string.IsNullOrWhiteSpace(name))
{
result = result.Where(p =>
p.ProductName != null &&
p.ProductName.ToLower().Contains(name.Trim().ToLower())
);
}
if (dateFrom.HasValue)
{
result = result.Where(p => p.ExpiryDate.Date >= dateFrom.Value.Date);
}
if (dateTo.HasValue)
{
result = result.Where(p => p.ExpiryDate.Date <= dateTo.Value.Date);
}
if (onlyExpired)
{
result = result.Where(p => p.ExpiryDate.Date < DateTime.Today);
}
return result
.OrderBy(p => p.ExpiryDate)
.ToList();
}
}
}