using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using LehrerApp.Core.Interfaces;
using LehrerApp.Core.Models;
using System.Collections.ObjectModel;
namespace LehrerApp.Desktop.ViewModels.Planning;
public sealed class TimetableUnitOption(Unit unit)
{
public Unit Model { get; } = unit;
public string Label { get; } = unit.Title;
public string Detail { get; } = unit.Status switch
{
UnitStatus.Active => "Laufende Einheit",
UnitStatus.Completed => "Abgeschlossene Einheit",
_ => "Geplante Einheit",
};
}
/// Ordnet eine direkt aus dem Stundenplan angelegte Stunde einer Einheit zu.
public partial class TimetableUnitPickerViewModel : ObservableObject
{
private readonly IUnitRepository _units;
private readonly Guid _groupId;
private readonly DateOnly _date;
public string ContextLabel { get; }
public ObservableCollection Units { get; } = [];
[ObservableProperty] private TimetableUnitOption? _selectedUnit;
[ObservableProperty] private string _newUnitTitle = "";
[ObservableProperty] private string _error = "";
public Unit? Result { get; private set; }
public bool ResultIsNew { get; private set; }
public bool HasUnits => Units.Count > 0;
public TimetableUnitPickerViewModel(IUnitRepository units, Guid groupId, string groupName,
DateOnly date, int period)
{
_units = units;
_groupId = groupId;
_date = date;
ContextLabel = $"{groupName} · {date:dd.MM.yyyy} · {period}. Stunde";
foreach (var unit in units.GetByGroup(groupId)
.OrderBy(u => u.Status == UnitStatus.Active ? 0 : u.Status == UnitStatus.Planned ? 1 : 2)
.ThenByDescending(u => u.StartDate)
.ThenBy(u => u.Title, StringComparer.CurrentCultureIgnoreCase))
Units.Add(new TimetableUnitOption(unit));
SelectedUnit = Units.FirstOrDefault();
}
[RelayCommand]
private void Save()
{
Error = "";
if (!string.IsNullOrWhiteSpace(NewUnitTitle))
{
Result = new Unit
{
GroupId = _groupId,
Title = NewUnitTitle.Trim(),
StartDate = _date,
Status = UnitStatus.Active,
};
// Erst speichern, wenn auch der anschließende Stunden-Dialog bestätigt wurde. So
// hinterlässt ein Abbruch keine leere Einheit.
ResultIsNew = true;
return;
}
if (SelectedUnit is null)
{
Error = "Bitte eine Einheit auswählen oder eine neue benennen.";
return;
}
Result = SelectedUnit.Model;
ResultIsNew = false;
}
}
public sealed record TimetableLessonRequest(Guid GroupId, DateOnly Date, int PeriodNumber);
public sealed record TimetableLessonMoveRequest(Lesson Lesson, int SelectedPeriod);