Commit fb06b394 authored by Maxime's avatar Maxime
Browse files

fix cleaning of games not being related to the creation

parent a9f35873
......@@ -9,13 +9,18 @@ namespace WebAPI.Model
public bool Ready { get => Players.Count == 2; }
public event Action<Game> NeedToBeCleaned;
public Game(string code)
{
Code = code;
Players = new List<Player>();
CheckAFKPlayers();
CheckEmptyGame();
}
public int AddPlayer()
{
if(Players.Count >= 2)
......@@ -39,5 +44,18 @@ namespace WebAPI.Model
});
}
private void CheckEmptyGame()
{
Task.Run(() =>
{
while (true)
{
Task.Delay(10000).Wait();
if (Players.Count == 0)
NeedToBeCleaned?.Invoke(this);
}
});
}
}
}
......@@ -28,36 +28,33 @@ namespace WebAPI.Model
Games = new ObservableCollection<Game>();
GamesAdmins = new List<GameAdmin>();
Games.CollectionChanged += Games_CollectionChanged;
CleanGames();
}
private void Games_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
GamesAdmins.Add(new GameAdmin(e.NewItems[0] as Game));
{
if (e.NewItems[0] is Game game)
{
GamesAdmins.Add(new GameAdmin(game));
game.NeedToBeCleaned += Game_NeedToBeCleaned;
}
}
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (Game game in e.OldItems)
{
game.NeedToBeCleaned -= Game_NeedToBeCleaned;
GamesAdmins.RemoveAll(x => x.Code == game.Code);
}
}
}
private void CleanGames()
private void Game_NeedToBeCleaned(Game obj)
{
Task.Run(() =>
{
while (true)
{
Task.Delay(60000).Wait();
var unusedGames = Games.Count(x => x.Players.Count == 0);
Trace.WriteLine($"Cleaning {unusedGames} unused game(s) out of {Games.Count}");
Games.Remove(x => x.Players.Count == 0);
}
});
Trace.WriteLine($"Cleaning 1 unused game out of {Games.Count}");
Games.Remove(obj);
}
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment