using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace Model.Players { public class PlayerManager : IManager { /// /// a collection of the players that this manager is in charge of /// private readonly List players = new(); /// /// add a new player /// /// player to be added /// added player public Task Add(Player toAdd) { if (toAdd is null) { throw new ArgumentNullException(nameof(toAdd), "param should not be null"); } if (players.Contains(toAdd)) { throw new ArgumentException("this username is already taken", nameof(toAdd)); } players.Add(toAdd); return Task.FromResult(toAdd); } /// /// finds the player with that name and returns it /// /// a player's unique name /// player with said name, or null if no such player was found public Task GetOneByName(string name) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("param should not be null or blank", nameof(name)); } Player result = players.FirstOrDefault(p => p.Name.ToUpper().Equals(name.ToUpper().Trim())); if (result == null) { return Task.FromResult(null); } return Task.FromResult(result); } /// /// get a READ ONLY enumerable of all players belonging to this manager /// so that the only way to modify the collection of players is to use this class's methods /// /// a readonly enumerable of all this manager's players public Task> GetAll() => Task.FromResult(new ReadOnlyCollection(players)); /// /// update a player from to /// /// player to be updated /// player in the state that it needs to be in after the update /// updated player public Task Update(Player before, Player after) { Player[] args = { before, after }; foreach (Player player in args) { if (player is null) { throw new ArgumentNullException(nameof(after), "param should not be null"); // could also be because of before, but one param had to be chosen as an example // and putting "player" there was raising a major code smell } } Remove(before); return Add(after); } /// /// remove a player /// /// player to be removed public void Remove(Player toRemove) { if (toRemove is null) { throw new ArgumentNullException(nameof(toRemove), "param should not be null"); } // the built-in Remove() method will use our redefined Equals(), using Name only players.Remove(toRemove); } public Task GetOneByID(Guid ID) { throw new NotImplementedException(); } } }