Files
Jugenddienst-Stunden/Jugenddienst Stunden/Views/StundenPage.xaml.cs

80 lines
2.3 KiB
C#

using Jugenddienst_Stunden.ViewModels;
using Jugenddienst_Stunden.Models;
using CommunityToolkit.Maui.Core;
using CommunityToolkit.Maui.Alerts;
namespace Jugenddienst_Stunden.Views;
/// <summary>
/// Code-Behind für die Stunden-Übersicht
/// </summary>
public partial class StundenPage : ContentPage {
/// <summary>
/// CTOR (für Shell/XAML DataTemplate erforderlich)
/// </summary>
public StundenPage() : this(
(Application.Current?.Handler?.MauiContext?.Services
?? throw new InvalidOperationException("DI container ist nicht verfügbar."))
.GetRequiredService<StundenViewModel>()) {
}
/// <summary>
/// CTOR (DI)
/// </summary>
public StundenPage(StundenViewModel vm) {
InitializeComponent();
BindingContext = vm;
vm.AlertEvent += Vm_AlertEvent;
vm.InfoEvent += Vm_InfoEvent;
}
private void Vm_AlertEvent(object? sender, string e) {
MainThread.BeginInvokeOnMainThread(async () => { await DisplayAlert("Fehler:", e, "OK"); });
}
private void Vm_InfoEvent(object? sender, string e) {
MainThread.BeginInvokeOnMainThread(async () => {
CancellationTokenSource cts = new CancellationTokenSource();
ToastDuration duration = ToastDuration.Short;
double fontSize = 16;
var toast = Toast.Make(e, duration, fontSize);
await toast.Show(cts.Token);
});
}
/// <summary>
/// Beim Laden der Seite den Titel setzen
/// </summary>
protected override async void OnAppearing() {
base.OnAppearing();
Title = Preferences.Default.Get("name", "Nicht") + " " + Preferences.Default.Get("surname", "eingeloggt");
if (!CheckLogin()) {
try {
await NavigateToTargetPage();
} catch (Exception ex) {
await DisplayAlert("Fehler:", ex.Message, "OK");
}
} else {
// Wenn eingeloggt, sicherstellen dass die Daten aktuell sind (besonders nach dem Login)
if (BindingContext is StundenViewModel vm) {
vm.RefreshProperties(); // Aktualisiert den Titel (Name/Vorname)
await vm.LoadDay(vm.DateToday);
}
}
}
private bool CheckLogin() {
return Preferences.Default.Get("apiKey", "") != "";
}
private Task NavigateToTargetPage() {
// Shell-Navigation statt Navigation.PushAsync
// Voraussetzung: LoginPage-Route ist in AppShell registriert (Routing.RegisterRoute(...))
return Shell.Current.GoToAsync(nameof(Views.LoginPage));
}
}