CollabVMDesktopClient/CollabVMClient/ViewModels/UserListViewModel.cs

78 lines
2.4 KiB
C#
Raw Normal View History

2023-08-29 08:52:35 -04:00
using CollabVMSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CollabVMClient.ViewModels
{
internal class UserListViewModel : ViewModelBase
{
public ObservableCollection<UserViewModel> Users { get; } = new ObservableCollection<UserViewModel>();
private string id;
public string Title => $"CollabVM - Users ({id})";
public UserListViewModel(string id)
{
this.id = id;
}
public void AddUser(string username, Rank rank)
{
// Needed if a user ranks up
RemoveUser(username);
Users.Add(new UserViewModel(username, rank));
}
public void RenameUser(string username, string newName)
{
var user = Users.First(u => u.Username == username);
user.Rename(newName);
}
public void RemoveUser(string username)
{
UserViewModel user;
try
{
user = Users.First(u => u.Username == username);
} catch (InvalidOperationException ex)
{
// just ignore it
return;
}
Users.Remove(user);
}
public void ParseTurnUpdate(TurnUpdateEventArgs e)
{
foreach (var user in Users)
{
user.SetTurnStatus(TurnStatus.None);
}
if (e.Queue.Length == 0) return;
var currentTurningUser = Users.First(u => u.Username == e.Queue[0].Username);
currentTurningUser.SetTurnStatus(TurnStatus.HasTurn);
for (int i = 1; i < e.Queue.Length; i++) {
var user = Users.First(u => u.Username == e.Queue[i].Username);
user.SetTurnStatus(TurnStatus.Waiting);
}
var newUsers = Users.OrderByDescending(i => GetSortIndex(i, e.Queue)).ToArray();
Users.Clear();
foreach (UserViewModel u in newUsers)
{
Users.Add(u);
}
}
public int GetSortIndex(UserViewModel u, User[] queue)
{
int i = Array.FindIndex(queue, x => x.Username == u.Username);
if (i == -1) return -1;
else return queue.Length - i;
}
}
}