using DbConnectionLibrairie; using Entities; using ManagerInterfaces; using Microsoft.EntityFrameworkCore; using Model; using OrderCriterias; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntityManagers { public class LobbyEntityManager(MyDbContext dbContext) : ILobbyManager { MyDbContext dbContext = dbContext; public async Task addLobby(LobbyEntity lobby) { var tmp = await dbContext.Lobbies.Where(l => l.IdCreator == lobby.IdCreator && l.Name == lobby.Name).FirstOrDefaultAsync(); if (tmp != null) // <=> he already exist { return tmp!; } dbContext.Lobbies.Add(lobby); await dbContext.SaveChangesAsync(); return await dbContext.Lobbies.Where(l => l.IdCreator == lobby.IdCreator && l.Name == lobby.Name).FirstAsync(); } public async Task<(int nbPages, IEnumerable? lobbies)> getLobbies(int nb, int count, LobbyOrderCriteria orderCriteria = LobbyOrderCriteria.ById) { int nbEl = getNbLobbies(); if (nb < 0 || count < 0 || nb > nbEl / count) return await Task.FromResult<(int nbPages, IEnumerable? lobbies)>((nbEl / count, null)); var tmp = dbContext.Lobbies; switch (orderCriteria) { case LobbyOrderCriteria.ById: tmp.OrderBy(l => l.Id); break; case LobbyOrderCriteria.ByName: tmp.OrderBy(l => l.Name); break; case LobbyOrderCriteria.ByNbJoueur: tmp.OrderBy(l => l.NbPlayers); break; } return await Task.FromResult<(int nbPages, IEnumerable? lobbies)>((nbEl / count, tmp.Skip((nb - 1) * count).Take(count))); } public async Task getLobby(int id) { return await dbContext.Lobbies.SingleOrDefaultAsync(l => l.Id == id); } public async Task getLobby(string name, int? idCreator) { if(name == null) { var tmp = dbContext.Lobbies.Where(l => l.Name == name && l.IdCreator != null); if (tmp.Count() == 0) return null; else if (tmp.Count() == 1) return tmp.First(); else throw new Exception("too much lobbies"); } return await dbContext.Lobbies.SingleOrDefaultAsync(l => l.Name == name && l.IdCreator == idCreator); } public int getNbLobbies() { return dbContext.Lobbies.CountAsync().Result; } public async Task removeLobby(LobbyEntity lobby) { var tmp = dbContext.Lobbies.Where(l => l.IdCreator == lobby.IdCreator && l.Name == lobby.Name).FirstOrDefaultAsync().Result; if (tmp == null) return await Task.FromResult(tmp); dbContext.Lobbies.Remove(tmp); await dbContext.SaveChangesAsync(); return await Task.FromResult(tmp); } public async Task removeLobby(int id) { var tmp = dbContext.Lobbies.Where(a => a.Id == id).FirstOrDefaultAsync().Result; if (tmp == null) return await Task.FromResult(tmp); dbContext.Lobbies.Remove(tmp); await dbContext.SaveChangesAsync(); return await Task.FromResult(tmp); } } }