presence/Presence.Desktop/ViewModels/MainWindowViewModel.cs
2024-12-10 20:47:49 +03:00

125 lines
3.7 KiB
C#

using domain.UseCase;
using Presence.Desktop.Models;
using System;
using System.Reactive.Linq;
using System.Reactive;
using System.Linq;
using ReactiveUI;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using System.Threading.Tasks;
namespace Presence.Desktop.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
private readonly IGroupUseCase _groupService;
private List<GroupPresenter> groupPresenters = new List<GroupPresenter>();
private ObservableCollection<GroupPresenter> _groups;
public ObservableCollection<GroupPresenter> Groups
{
get => _groups;
set => this.RaiseAndSetIfChanged(ref _groups, value);
}
private GroupPresenter? _selectedGroupItem;
public GroupPresenter? SelectedGroupItem
{
get => _selectedGroupItem;
set => this.RaiseAndSetIfChanged(ref _selectedGroupItem, value);
}
private ObservableCollection<StudentPresenter> _students;
public ObservableCollection<StudentPresenter> Students
{
get => _students;
set => this.RaiseAndSetIfChanged(ref _students, value);
}
public Interaction<Unit, string?> ShowOpenFileDialog;
private string? _selectedFile;
public string? SelectedFile
{
get => _selectedFile;
set => this.RaiseAndSetIfChanged(ref _selectedFile, value);
}
public ICommand OpenFileDialog { get; }
public MainWindowViewModel()
{
_groupService = null;
_groups = new();
_students = new();
OpenFileDialog = ReactiveCommand.CreateFromTask(SelectFile);
}
public MainWindowViewModel(IGroupUseCase gService)
{
_groupService = gService;
ShowOpenFileDialog = new Interaction<Unit, string?>();
OpenFileDialog = ReactiveCommand.CreateFromTask(SelectFile);
_students = new();
this.WhenAnyValue(vm => vm.SelectedGroupItem)
.Subscribe(_ =>
{
RefreshGroups();
SetStudents();
});
}
private void RefreshGroups()
{
groupPresenters.Clear();
foreach (var item in _groupService.GetGroupsWithStudents())
{
GroupPresenter groupPresenter = new GroupPresenter
{
Id = item.Id,
Name = item.Name,
students = item.Users?.Select(u => new StudentPresenter
{
Id = u.Id,
FirstName = u.FirstName,
LastName = u.LastName,
Patronymic = u.Patronymic,
Group = new GroupPresenter
{
Id = item.Id,
Name = item.Name
}
})
};
groupPresenters.Add(groupPresenter);
}
_groups = new(groupPresenters);
}
private void SetStudents()
{
if (SelectedGroupItem == null) return;
if (SelectedGroupItem.students == null) return;
Students.Clear();
foreach (var student in SelectedGroupItem.students)
Students.Add(student);
}
private async Task SelectFile()
{
SelectedFile = await ShowOpenFileDialog.Handle(Unit.Default);
if (SelectedFile is object)
{
}
}
}
}