using Android.Content; using AndroidX.Core.App; using cfs_tracker.Data; using cfs_tracker.Models; using Microsoft.Maui; namespace cfs_tracker.Platforms.Android; [BroadcastReceiver(Enabled = true, Exported = false)] public sealed class CfsNotificationReceiver : BroadcastReceiver { public override void OnReceive(Context? context, Intent? intent) { if (context is null || intent is null) return; switch (intent.Action) { case AndroidNotificationScheduler.ActionShowNotification: HandleAlarmTriggered(context, intent); break; case AndroidNotificationScheduler.ActionSaveStatus: HandleSaveStatus(context, intent); break; } } private static void HandleAlarmTriggered(Context context, Intent intent) { var scheduleId = intent.GetIntExtra(AndroidNotificationScheduler.ExtraScheduleId, 0); var dayOfWeek = (DayOfWeek)intent.GetIntExtra(AndroidNotificationScheduler.ExtraDayOfWeek, (int)DayOfWeek.Monday); var hour = intent.GetIntExtra(AndroidNotificationScheduler.ExtraHour, 9); var minute = intent.GetIntExtra(AndroidNotificationScheduler.ExtraMinute, 0); AndroidNotificationScheduler.ShowNotification( context, scheduleId, dayOfWeek, "Wie geht es dir?", "Tippe, um deinen Status einzutragen."); AndroidNotificationScheduler.ScheduleNextAlarm( context, scheduleId, dayOfWeek, hour, minute); } private void HandleSaveStatus(Context context, Intent intent) { var pendingResult = GoAsync(); if (pendingResult is null) return; _ = Task.Run(async () => { try { var statusText = intent.GetStringExtra(AndroidNotificationScheduler.ExtraStatus) ?? string.Empty; var notificationId = intent.GetIntExtra(AndroidNotificationScheduler.ExtraNotificationId, 0); if (!TryParseState(statusText, out var state)) return; var services = IPlatformApplication.Current?.Services; var repository = services?.GetService(typeof(HealthEntryRepository)) as HealthEntryRepository; if (repository is null) return; await repository.AddQuickEntryAsync( state: state, activityId: null, activityDurationMinutes: null, symptomIds: null, timestamp: DateTime.Now, source: EntrySource.App); var notificationManager = NotificationManagerCompat.From(context); notificationManager?.Cancel(notificationId); } finally { pendingResult.Finish(); } }); } private static bool TryParseState(string? value, out HealthState state) { switch ((value ?? string.Empty).Trim().ToLowerInvariant()) { case "green": case "gruen": case "grün": state = HealthState.Green; return true; case "yellow": case "gelb": state = HealthState.Yellow; return true; case "red": case "rot": state = HealthState.Red; return true; case "gray": case "grey": case "grau": case "schwarz": state = HealthState.Gray; return true; default: state = default; return false; } } }