using DutchTreat.Data.Entities; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DutchTreat.Data { public class DutchRepository : IDutchRepository { private readonly DutchContext _ctx; private readonly ILogger _logger; public DutchRepository(DutchContext ctx, ILogger logger) { _ctx = ctx; _logger = logger; } public void AddEntity(Order model) { _ctx.Add(model); } public IEnumerable GetAllOrders(bool includedItems) { try { if (includedItems) { _logger.LogInformation("GetAllOrders was called"); return _ctx.Orders .Include(o => o.Items) .ThenInclude(i => i.Product) .ToList(); } else { return _ctx.Orders.ToList(); } } catch (Exception ex) { _logger.LogError($"Failed to get all orders: {ex}"); return null; } } public IEnumerable GetAllOrdersByUser(string username, bool includedItems) { try { if (includedItems) { _logger.LogInformation("GetAllOrdersByUser was called"); return _ctx.Orders .Where(o => o.User.UserName == username) .Include(o => o.Items) .ThenInclude(i => i.Product) .ToList(); } else { return _ctx.Orders .Where(o => o.User.UserName == username) .ToList(); } } catch (Exception ex) { _logger.LogError($"Failed to get all orders: {ex}"); return null; } } public IEnumerable GetAllProducts() { try { _logger.LogInformation("GetAllProduct was called"); return _ctx.Products .OrderBy(p => p.Title) .ToList(); } catch (Exception ex) { _logger.LogError($"Failed to get all products: {ex}"); return null; } } public Order GetOrderById(string username, int id) { return _ctx.Orders .Include(o => o.Items) .ThenInclude(i => i.Product) .Where(o => o.Id == id && o.User.UserName == username) .FirstOrDefault(); } public IEnumerable GetProductsByCategory(string category) { return _ctx.Products .Where(p => p.Category == category) .ToList(); } public bool SaveAll() { return _ctx.SaveChanges() > 0; } } }