302 lines
10 KiB
C#
302 lines
10 KiB
C#
using cfs_tracker.Data;
|
|
using cfs_tracker.Helpers;
|
|
using cfs_tracker.Models;
|
|
using cfs_tracker.Services;
|
|
using CommunityToolkit.Mvvm.ComponentModel;
|
|
using CommunityToolkit.Mvvm.Input;
|
|
using Microsoft.Maui.ApplicationModel;
|
|
using System.Collections.ObjectModel;
|
|
|
|
namespace cfs_tracker.ViewModels;
|
|
|
|
public partial class YearViewModel : ObservableObject
|
|
{
|
|
private readonly HealthEntryRepository _healthEntryRepository;
|
|
private readonly AppearanceService _appearanceService;
|
|
private readonly CalendarStateService _calendarStateService;
|
|
private readonly IPdfExportService _pdfExportService;
|
|
private CancellationTokenSource? _refreshCancellationTokenSource;
|
|
|
|
[ObservableProperty]
|
|
private DateTime selectedDate;
|
|
|
|
[ObservableProperty]
|
|
private string headerText = string.Empty;
|
|
|
|
public ObservableCollection<MonthSectionViewModel> Months { get; } = new();
|
|
|
|
public IAsyncRelayCommand PreviousYearCommand { get; }
|
|
public IAsyncRelayCommand NextYearCommand { get; }
|
|
public IAsyncRelayCommand TodayCommand { get; }
|
|
public IAsyncRelayCommand ExportPdfCommand { get; }
|
|
public IAsyncRelayCommand<MonthCellViewModel> OpenDayCommand { get; }
|
|
|
|
public YearViewModel(
|
|
HealthEntryRepository healthEntryRepository,
|
|
AppearanceService appearanceService,
|
|
CalendarStateService calendarStateService,
|
|
IPdfExportService pdfExportService)
|
|
{
|
|
_healthEntryRepository = healthEntryRepository;
|
|
_appearanceService = appearanceService;
|
|
_calendarStateService = calendarStateService;
|
|
_pdfExportService = pdfExportService;
|
|
|
|
PreviousYearCommand = new AsyncRelayCommand(PreviousYearAsync);
|
|
NextYearCommand = new AsyncRelayCommand(NextYearAsync);
|
|
TodayCommand = new AsyncRelayCommand(TodayAsync);
|
|
ExportPdfCommand = new AsyncRelayCommand(ExportAsync);
|
|
OpenDayCommand = new AsyncRelayCommand<MonthCellViewModel>(OpenDayAsync);
|
|
|
|
_calendarStateService.SelectedDateChanged += HandleSharedDateChanged;
|
|
SelectedDate = _calendarStateService.SelectedDate.Date;
|
|
UpdateHeader();
|
|
}
|
|
|
|
partial void OnSelectedDateChanged(DateTime value)
|
|
{
|
|
UpdateHeader();
|
|
}
|
|
|
|
public async Task RefreshAsync()
|
|
{
|
|
var refreshCancellationTokenSource = BeginRefresh();
|
|
var cancellationToken = refreshCancellationTokenSource.Token;
|
|
|
|
SelectedDate = _calendarStateService.SelectedDate.Date;
|
|
UpdateHeader();
|
|
|
|
try
|
|
{
|
|
var selectedYear = SelectedDate.Year;
|
|
var sections = CreateMonthSections(selectedYear);
|
|
|
|
Months.Clear();
|
|
foreach (var section in sections)
|
|
Months.Add(section);
|
|
|
|
for (var monthNumber = 1; monthNumber <= sections.Count; monthNumber++)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await LoadMonthSectionAsync(
|
|
sections[monthNumber - 1],
|
|
selectedYear,
|
|
monthNumber,
|
|
cancellationToken);
|
|
}
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
// Ein neueres Refresh hat diese Aktualisierung ersetzt.
|
|
}
|
|
finally
|
|
{
|
|
EndRefresh(refreshCancellationTokenSource);
|
|
}
|
|
}
|
|
|
|
private void UpdateHeader()
|
|
{
|
|
HeaderText = DateHelper.ToGermanYear(SelectedDate);
|
|
}
|
|
|
|
private async Task OpenDayAsync(MonthCellViewModel? item)
|
|
{
|
|
if (item is null || !item.IsCurrentMonth)
|
|
return;
|
|
|
|
SelectedDate = item.Date.Date;
|
|
_calendarStateService.SelectedDate = SelectedDate;
|
|
await Shell.Current.GoToAsync("//day");
|
|
}
|
|
|
|
private async Task ExportAsync()
|
|
{
|
|
var result = await _pdfExportService.ExportYearAsync(SelectedDate);
|
|
await ExportUiHelper.ShowExportSavedActionsAsync(result);
|
|
}
|
|
|
|
private async Task PreviousYearAsync()
|
|
{
|
|
SelectedDate = new DateTime(SelectedDate.Year - 1, SelectedDate.Month, 1);
|
|
_calendarStateService.SelectedDate = SelectedDate;
|
|
await RefreshAsync();
|
|
}
|
|
|
|
private async Task NextYearAsync()
|
|
{
|
|
SelectedDate = new DateTime(SelectedDate.Year + 1, SelectedDate.Month, 1);
|
|
_calendarStateService.SelectedDate = SelectedDate;
|
|
await RefreshAsync();
|
|
}
|
|
|
|
private async Task TodayAsync()
|
|
{
|
|
var today = DateTime.Today;
|
|
SelectedDate = today;
|
|
_calendarStateService.SelectedDate = today;
|
|
await Shell.Current.GoToAsync("//day");
|
|
}
|
|
|
|
private void HandleSharedDateChanged(DateTime date)
|
|
{
|
|
MainThread.BeginInvokeOnMainThread(async () =>
|
|
{
|
|
if (SelectedDate.Date == date.Date)
|
|
return;
|
|
|
|
SelectedDate = date.Date;
|
|
await RefreshAsync();
|
|
});
|
|
}
|
|
|
|
private CancellationTokenSource BeginRefresh()
|
|
{
|
|
var refreshCancellationTokenSource = new CancellationTokenSource();
|
|
var previousRefresh = Interlocked.Exchange(ref _refreshCancellationTokenSource, refreshCancellationTokenSource);
|
|
|
|
previousRefresh?.Cancel();
|
|
previousRefresh?.Dispose();
|
|
|
|
return refreshCancellationTokenSource;
|
|
}
|
|
|
|
private void EndRefresh(CancellationTokenSource refreshCancellationTokenSource)
|
|
{
|
|
if (ReferenceEquals(_refreshCancellationTokenSource, refreshCancellationTokenSource))
|
|
_refreshCancellationTokenSource = null;
|
|
|
|
refreshCancellationTokenSource.Dispose();
|
|
}
|
|
|
|
private List<MonthSectionViewModel> CreateMonthSections(int year)
|
|
{
|
|
return Enumerable.Range(1, 12)
|
|
.Select(monthNumber => new MonthSectionViewModel
|
|
{
|
|
Title = new DateTime(year, monthNumber, 1).ToString("MMMM", LocalizationService.GetCurrentCulture()),
|
|
IsLoading = true
|
|
})
|
|
.ToList();
|
|
}
|
|
|
|
private async Task LoadMonthSectionAsync(
|
|
MonthSectionViewModel section,
|
|
int year,
|
|
int monthNumber,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var monthStart = new DateTime(year, monthNumber, 1);
|
|
var monthEnd = monthStart.AddMonths(1);
|
|
var entries = await _healthEntryRepository.GetEntriesBetweenAsync(monthStart, monthEnd);
|
|
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
|
|
var cells = BuildMonthCells(monthStart, entries);
|
|
|
|
await MainThread.InvokeOnMainThreadAsync(() =>
|
|
{
|
|
if (cancellationToken.IsCancellationRequested)
|
|
return;
|
|
|
|
section.ReplaceCells(cells);
|
|
});
|
|
}
|
|
|
|
private List<MonthCellViewModel> BuildMonthCells(DateTime monthStart, IReadOnlyList<HealthEntry> entries)
|
|
{
|
|
var cells = new List<MonthCellViewModel>();
|
|
var daysInMonth = DateTime.DaysInMonth(monthStart.Year, monthStart.Month);
|
|
var entriesByDay = entries
|
|
.GroupBy(x => x.EntryDate.Date)
|
|
.ToDictionary(group => group.Key, group => (IReadOnlyCollection<HealthEntry>)group.ToList());
|
|
|
|
var leadingEmptyCells = GetMondayBasedColumnIndex(monthStart.DayOfWeek);
|
|
for (var i = 0; i < leadingEmptyCells; i++)
|
|
cells.Add(CreatePlaceholderCell());
|
|
|
|
for (var day = 1; day <= daysInMonth; day++)
|
|
{
|
|
var date = new DateTime(monthStart.Year, monthStart.Month, day);
|
|
var dayEntries = entriesByDay.TryGetValue(date.Date, out var matches)
|
|
? matches
|
|
: Array.Empty<HealthEntry>();
|
|
var worstState = CalculateWorstState(dayEntries);
|
|
|
|
cells.Add(new MonthCellViewModel
|
|
{
|
|
Date = date,
|
|
DayNumberText = date.Day.ToString(),
|
|
IsCurrentMonth = true,
|
|
IsToday = date.Date == DateTime.Today,
|
|
HasEntries = dayEntries.Count > 0,
|
|
BackgroundColor = GetCellBackgroundColor(worstState),
|
|
TextColor = GetCellTextColor(worstState),
|
|
BorderColor = date.Date == DateTime.Today
|
|
? _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42")
|
|
: _appearanceService.GetColor(AppearanceKeys.Border, "#2A3E55")
|
|
});
|
|
}
|
|
|
|
while (cells.Count % 7 != 0)
|
|
cells.Add(CreatePlaceholderCell());
|
|
|
|
return cells;
|
|
}
|
|
|
|
private Color GetCellBackgroundColor(HealthState? state) => state switch
|
|
{
|
|
HealthState.Green => _appearanceService.GetColor(AppearanceKeys.StateGreen, "#4E8B69"),
|
|
HealthState.Yellow => _appearanceService.GetColor(AppearanceKeys.StateYellow, "#B89A42"),
|
|
HealthState.Red => _appearanceService.GetColor(AppearanceKeys.StateRed, "#A85C5C"),
|
|
HealthState.Gray => _appearanceService.GetColor(AppearanceKeys.StateGray, "#1F242B"),
|
|
_ => _appearanceService.GetColor(AppearanceKeys.SurfaceBackgroundAlt, "#1F242B")
|
|
};
|
|
|
|
private Color GetCellTextColor(HealthState? state) => state switch
|
|
{
|
|
HealthState.Yellow => Colors.Black,
|
|
HealthState.Green => Colors.White,
|
|
HealthState.Red => Colors.White,
|
|
HealthState.Gray => Colors.White,
|
|
_ => _appearanceService.GetColor(AppearanceKeys.TextPrimary, "#DCE7F3")
|
|
};
|
|
|
|
private static int GetMondayBasedColumnIndex(DayOfWeek dayOfWeek)
|
|
{
|
|
return dayOfWeek == DayOfWeek.Sunday ? 6 : ((int)dayOfWeek - 1);
|
|
}
|
|
|
|
private static HealthState? CalculateWorstState(IReadOnlyCollection<HealthEntry> entries)
|
|
{
|
|
if (entries.Count == 0)
|
|
return null;
|
|
|
|
if (entries.Any(x => x.State == HealthState.Gray))
|
|
return HealthState.Gray;
|
|
|
|
if (entries.Any(x => x.State == HealthState.Red))
|
|
return HealthState.Red;
|
|
|
|
if (entries.Any(x => x.State == HealthState.Yellow))
|
|
return HealthState.Yellow;
|
|
|
|
return HealthState.Green;
|
|
}
|
|
|
|
private static MonthCellViewModel CreatePlaceholderCell()
|
|
{
|
|
return new MonthCellViewModel
|
|
{
|
|
Date = DateTime.MinValue,
|
|
DayNumberText = string.Empty,
|
|
IsCurrentMonth = false,
|
|
IsToday = false,
|
|
HasEntries = false,
|
|
BackgroundColor = Colors.Transparent,
|
|
TextColor = Colors.Transparent,
|
|
BorderColor = Colors.Transparent
|
|
};
|
|
}
|
|
}
|