446 lines
18 KiB
C#
446 lines
18 KiB
C#
#nullable enable
|
||
using System;
|
||
using System.Collections.ObjectModel;
|
||
using System.Collections.Specialized;
|
||
using System.ComponentModel;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
using System.Windows.Data;
|
||
using System.Windows.Input;
|
||
using System.Windows.Threading;
|
||
using ReminderOrganizer.Core;
|
||
using ReminderOrganizer.Models;
|
||
using ReminderOrganizer.Services;
|
||
|
||
namespace ReminderOrganizer.ViewModels
|
||
{
|
||
public class MainViewModel : ViewModelBase
|
||
{
|
||
public const string DiscordUrl = "https://discord.gg/Ej4JPmCZva";
|
||
|
||
private readonly IDataService _dataService;
|
||
private readonly INotificationService _notificationService;
|
||
private readonly ILocalizationService _localizationService;
|
||
private readonly IAutostartService _autostartService;
|
||
private readonly DispatcherTimer _reminderTimer;
|
||
|
||
private AppData _appData = new();
|
||
private Folder? _selectedFolder;
|
||
private ReminderTask? _selectedTask;
|
||
private bool _isLoading;
|
||
private ICollectionView? _selectedFolderTasksView;
|
||
|
||
public bool IsLoading
|
||
{
|
||
get => _isLoading;
|
||
set => SetProperty(ref _isLoading, value);
|
||
}
|
||
|
||
public ObservableCollection<Folder> Folders => _appData.Folders;
|
||
|
||
public Folder? SelectedFolder
|
||
{
|
||
get => _selectedFolder;
|
||
set
|
||
{
|
||
var old = _selectedFolder;
|
||
if (SetProperty(ref _selectedFolder, value))
|
||
{
|
||
if (old != null) old.Tasks.CollectionChanged -= OnSelectedTasksChanged;
|
||
if (value != null) value.Tasks.CollectionChanged += OnSelectedTasksChanged;
|
||
_selectedFolderTasksView = CreateSortedView(value);
|
||
OnPropertyChanged(nameof(SelectedFolderTasks));
|
||
OnPropertyChanged(nameof(SelectedFolderTasksView));
|
||
OnPropertyChanged(nameof(SelectedFolderName));
|
||
OnPropertyChanged(nameof(TaskCountText));
|
||
OnPropertyChanged(nameof(HasSelectedFolder));
|
||
}
|
||
}
|
||
}
|
||
|
||
private void OnSelectedTasksChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||
{
|
||
OnPropertyChanged(nameof(TaskCountText));
|
||
}
|
||
|
||
private static ICollectionView? CreateSortedView(Folder? folder)
|
||
{
|
||
if (folder == null) return null;
|
||
var view = new ListCollectionView(folder.Tasks);
|
||
view.SortDescriptions.Add(new SortDescription(nameof(ReminderTask.IsNotified), ListSortDirection.Ascending));
|
||
view.SortDescriptions.Add(new SortDescription(nameof(ReminderTask.ReminderDate), ListSortDirection.Ascending));
|
||
view.IsLiveSorting = true;
|
||
view.LiveSortingProperties.Add(nameof(ReminderTask.IsNotified));
|
||
view.LiveSortingProperties.Add(nameof(ReminderTask.ReminderDate));
|
||
return view;
|
||
}
|
||
|
||
public ReminderTask? SelectedTask
|
||
{
|
||
get => _selectedTask;
|
||
set => SetProperty(ref _selectedTask, value);
|
||
}
|
||
|
||
public ObservableCollection<ReminderTask>? SelectedFolderTasks => SelectedFolder?.Tasks;
|
||
|
||
/// <summary>Tasks of the selected folder: open first, then by date.</summary>
|
||
public ICollectionView? SelectedFolderTasksView => _selectedFolderTasksView;
|
||
|
||
public bool HasSelectedFolder => SelectedFolder != null;
|
||
|
||
public string SelectedFolderName => SelectedFolder?.Name ?? L("Welcome");
|
||
|
||
public string TaskCountText => $"{SelectedFolder?.Tasks.Count ?? 0} {L("Tasks")}";
|
||
|
||
public string AddFolderText => L("AddFolder");
|
||
public string AddTaskText => L("AddTask");
|
||
public string AutostartText => L("Autostart");
|
||
public string ExitText => L("Exit");
|
||
public string FileText => L("File");
|
||
public string SettingsText => L("Settings");
|
||
public string LanguageText => L("Language");
|
||
public string GermanText => L("German");
|
||
public string EnglishText => L("English");
|
||
public string DeleteText => L("Delete");
|
||
public string RenameText => L("Rename");
|
||
public string ViewText => L("View");
|
||
public string DarkModeText => L("DarkMode");
|
||
public string LightModeText => L("LightMode");
|
||
public string AddTaskToFolderText => L("AddTaskToFolder");
|
||
public string MinimizeTooltip => L("Minimize");
|
||
public string MaximizeTooltip => L("Maximize");
|
||
public string CloseTooltip => L("Close");
|
||
public string CreateTaskHint => L("CreateTaskHint");
|
||
public string NoTasks => L("NoTasks");
|
||
public string FoldersText => L("Folders");
|
||
public string NameColumnText => L("Name");
|
||
public string DateColumnText => L("Date");
|
||
public string EditTaskTooltip => L("EditTaskTooltip");
|
||
public string DeleteTaskTooltip => L("DeleteTaskTooltip");
|
||
public string DoneTooltip => L("DoneTooltip");
|
||
public string InfoText => L("Info");
|
||
public string DiscordText => L("Discord");
|
||
public string ImportText => L("Import");
|
||
public string ExportText => L("Export");
|
||
public string ImportCsvText => L("ImportCsv");
|
||
public string ExportCsvText => L("ExportCsv");
|
||
public string TestNotificationText => L("TestNotification");
|
||
public string AppTitleText => L("AppTitle");
|
||
public string RecurringTaskTooltipText => L("RecurringTaskTooltip");
|
||
public string CopyrightText => $"© {DateTime.Now.Year} Michael Media";
|
||
public string VersionText => "v" + (typeof(MainViewModel).Assembly.GetName().Version?.ToString(3) ?? "");
|
||
|
||
public bool IsGerman => _localizationService.CurrentLanguage == "de";
|
||
public bool IsEnglish => _localizationService.CurrentLanguage == "en";
|
||
public bool IsAutostartEnabled => _autostartService.IsAutostartEnabled;
|
||
|
||
private bool _isDarkMode = true;
|
||
public bool IsDarkMode
|
||
{
|
||
get => _isDarkMode;
|
||
set
|
||
{
|
||
if (SetProperty(ref _isDarkMode, value))
|
||
{
|
||
ThemeChanged?.Invoke(this, value);
|
||
_appData.IsDarkMode = value;
|
||
_ = SaveAsync();
|
||
}
|
||
}
|
||
}
|
||
|
||
public event EventHandler<bool>? ThemeChanged;
|
||
public event EventHandler<ReminderTask?>? EditTaskRequested;
|
||
|
||
public ICommand AddFolderCommand { get; }
|
||
public ICommand AddTaskCommand { get; }
|
||
public ICommand AddTaskToFolderCommand { get; }
|
||
public ICommand DeleteTaskCommand { get; }
|
||
public ICommand EditTaskCommand { get; }
|
||
public ICommand ToggleDoneCommand { get; }
|
||
public ICommand ToggleAutostartCommand { get; }
|
||
public ICommand ExitCommand { get; }
|
||
public ICommand DeleteFolderCommand { get; }
|
||
public ICommand RenameFolderCommand { get; }
|
||
public ICommand SaveFolderCommand { get; }
|
||
public ICommand SetLanguageDeCommand { get; }
|
||
public ICommand SetLanguageEnCommand { get; }
|
||
public ICommand ToggleDarkModeCommand { get; }
|
||
public ICommand MoveTaskToFolderCommand { get; }
|
||
public ICommand TestNotificationCommand { get; }
|
||
public ICommand ImportCsvCommand { get; }
|
||
public ICommand ExportCsvCommand { get; }
|
||
public ICommand OpenDiscordCommand { get; }
|
||
|
||
public MainViewModel(
|
||
IDataService dataService,
|
||
INotificationService notificationService,
|
||
ILocalizationService localizationService,
|
||
IAutostartService autostartService)
|
||
{
|
||
_dataService = dataService;
|
||
_notificationService = notificationService;
|
||
_localizationService = localizationService;
|
||
_autostartService = autostartService;
|
||
|
||
// Empty name = refresh every binding (all texts depend on the language).
|
||
_localizationService.StringsChanged += (s, e) => OnPropertyChanged(string.Empty);
|
||
|
||
AddFolderCommand = new RelayCommand(AddFolder);
|
||
AddTaskCommand = new RelayCommand(AddTask, () => SelectedFolder != null);
|
||
AddTaskToFolderCommand = new RelayCommand<Folder>(AddTaskToFolder);
|
||
DeleteTaskCommand = new RelayCommand<ReminderTask>(DeleteTask);
|
||
EditTaskCommand = new RelayCommand<ReminderTask>(EditTask);
|
||
ToggleDoneCommand = new RelayCommand<ReminderTask>(t => { _ = SaveAsync(); });
|
||
DeleteFolderCommand = new RelayCommand(DeleteFolder, () => SelectedFolder != null);
|
||
RenameFolderCommand = new RelayCommand(RenameFolder, () => SelectedFolder != null);
|
||
SaveFolderCommand = new RelayCommand(async () => await SaveAsync());
|
||
ToggleAutostartCommand = new RelayCommand(ToggleAutostart);
|
||
SetLanguageDeCommand = new RelayCommand(() => _localizationService.SetLanguage("de"));
|
||
SetLanguageEnCommand = new RelayCommand(() => _localizationService.SetLanguage("en"));
|
||
ToggleDarkModeCommand = new RelayCommand(() => IsDarkMode = !IsDarkMode);
|
||
ExitCommand = new RelayCommand(() => Application.Current.Shutdown());
|
||
MoveTaskToFolderCommand = new RelayCommand<(ReminderTask, Folder)>(MoveTaskToFolder);
|
||
TestNotificationCommand = new RelayCommand(TestNotification);
|
||
ImportCsvCommand = new RelayCommand(ImportCsv);
|
||
ExportCsvCommand = new RelayCommand(ExportCsv);
|
||
OpenDiscordCommand = new RelayCommand(OpenDiscord);
|
||
|
||
_reminderTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
|
||
_reminderTimer.Tick += (s, e) => CheckReminders();
|
||
}
|
||
|
||
public async Task InitializeAsync()
|
||
{
|
||
IsLoading = true;
|
||
_appData = await _dataService.LoadAsync();
|
||
bool firstRun = string.IsNullOrEmpty(_appData.Language) || _appData.IsDarkMode == null || _appData.Folders.Count == 0;
|
||
_appData.IsDarkMode ??= SystemPrefs.IsDarkMode();
|
||
_localizationService.Initialize(_appData); // fills Language from Windows if empty
|
||
|
||
if (_appData.Folders.Count == 0)
|
||
_appData.Folders.Add(new Folder(L("MyTasks")));
|
||
if (firstRun)
|
||
await SaveAsync();
|
||
|
||
_isDarkMode = _appData.IsDarkMode.Value;
|
||
OnPropertyChanged(nameof(IsDarkMode));
|
||
OnPropertyChanged(nameof(Folders));
|
||
SelectedFolder = _appData.Folders.FirstOrDefault();
|
||
|
||
CheckReminders(); // catch up on reminders missed while the app was closed
|
||
_reminderTimer.Start();
|
||
IsLoading = false;
|
||
}
|
||
|
||
public string L(string key) => _localizationService.GetString(key);
|
||
|
||
private bool Confirm(string message) =>
|
||
MessageBox.Show(Application.Current.MainWindow, message, L("AppTitle"),
|
||
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
|
||
|
||
private string? AskName(string title, string current)
|
||
{
|
||
var dialog = new InputDialog(title, L("NewName"), current, IsDarkMode) { Owner = Application.Current.MainWindow };
|
||
if (dialog.ShowDialog() != true) return null;
|
||
var name = dialog.ResponseText?.Trim();
|
||
return string.IsNullOrEmpty(name) ? null : name;
|
||
}
|
||
|
||
private void AddFolder()
|
||
{
|
||
var name = AskName(L("NewFolder"), L("NewFolder"));
|
||
if (name == null) return;
|
||
var folder = new Folder(name);
|
||
_appData.Folders.Add(folder);
|
||
SelectedFolder = folder;
|
||
_ = SaveAsync();
|
||
}
|
||
|
||
private void RenameFolder()
|
||
{
|
||
if (SelectedFolder == null) return;
|
||
var name = AskName(L("RenameFolder"), SelectedFolder.Name);
|
||
if (name == null) return;
|
||
SelectedFolder.Name = name;
|
||
OnPropertyChanged(nameof(SelectedFolderName));
|
||
_ = SaveAsync();
|
||
}
|
||
|
||
private void DeleteFolder()
|
||
{
|
||
if (SelectedFolder == null) return;
|
||
if (SelectedFolder.Tasks.Count > 0 &&
|
||
!Confirm(string.Format(L("ConfirmDeleteFolder"), SelectedFolder.Name, SelectedFolder.Tasks.Count)))
|
||
return;
|
||
|
||
_appData.Folders.Remove(SelectedFolder);
|
||
SelectedFolder = _appData.Folders.FirstOrDefault();
|
||
_ = SaveAsync();
|
||
}
|
||
|
||
private void AddTask() => AddTaskInternal(SelectedFolder);
|
||
|
||
private void AddTaskToFolder(Folder? folder) => AddTaskInternal(folder);
|
||
|
||
private void AddTaskInternal(Folder? folder)
|
||
{
|
||
if (folder == null)
|
||
{
|
||
MessageBox.Show(L("NoFolderSelectFirst"), L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Information);
|
||
return;
|
||
}
|
||
|
||
var taskWindow = new TaskWindow(null, IsDarkMode) { Owner = Application.Current.MainWindow };
|
||
if (taskWindow.ShowDialog() == true)
|
||
{
|
||
folder.Tasks.Add(taskWindow.TaskResult);
|
||
_ = SaveAsync();
|
||
}
|
||
}
|
||
|
||
private void DeleteTask(ReminderTask? task)
|
||
{
|
||
if (task == null) return;
|
||
var folder = _appData.Folders.FirstOrDefault(f => f.Tasks.Contains(task));
|
||
if (folder == null) return;
|
||
if (!Confirm(string.Format(L("ConfirmDeleteTask"), task.Name))) return;
|
||
folder.Tasks.Remove(task);
|
||
_ = SaveAsync();
|
||
}
|
||
|
||
private void MoveTaskToFolder((ReminderTask Task, Folder TargetFolder) args)
|
||
{
|
||
var (task, targetFolder) = args;
|
||
if (task == null || targetFolder == null) return;
|
||
|
||
var sourceFolder = _appData.Folders.FirstOrDefault(f => f.Tasks.Contains(task));
|
||
if (sourceFolder == null || sourceFolder == targetFolder) return;
|
||
|
||
sourceFolder.Tasks.Remove(task);
|
||
targetFolder.Tasks.Add(task);
|
||
_ = SaveAsync();
|
||
}
|
||
|
||
private void EditTask(ReminderTask? task)
|
||
{
|
||
if (task == null) return;
|
||
SelectedTask = task;
|
||
EditTaskRequested?.Invoke(this, task);
|
||
}
|
||
|
||
private void ToggleAutostart()
|
||
{
|
||
_autostartService.ToggleAutostart();
|
||
OnPropertyChanged(nameof(IsAutostartEnabled));
|
||
_notificationService.ShowNotification(L("AppTitle"),
|
||
_autostartService.IsAutostartEnabled ? L("AutostartEnabled") : L("AutostartDisabled"));
|
||
}
|
||
|
||
private void CheckReminders()
|
||
{
|
||
var due = ReminderTask.ProcessDue(_appData.Folders, DateTime.Now);
|
||
foreach (var task in due)
|
||
{
|
||
var body = string.IsNullOrWhiteSpace(task.Description) ? L("Reminder") : task.Description;
|
||
_notificationService.ShowNotification($"🔔 {task.Name}", body);
|
||
}
|
||
if (due.Count > 0) _ = SaveAsync();
|
||
}
|
||
|
||
private void TestNotification()
|
||
{
|
||
_notificationService.ShowNotification(L("TestNotificationTitle"), L("TestNotificationMessage"));
|
||
}
|
||
|
||
private void OpenDiscord()
|
||
{
|
||
try
|
||
{
|
||
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
|
||
{
|
||
FileName = DiscordUrl,
|
||
UseShellExecute = true
|
||
});
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
System.Diagnostics.Debug.WriteLine($"[OpenDiscord] {ex.Message}");
|
||
}
|
||
}
|
||
|
||
private void ImportCsv()
|
||
{
|
||
var dialog = new Microsoft.Win32.OpenFileDialog
|
||
{
|
||
Filter = "CSV (*.csv)|*.csv|All Files (*.*)|*.*",
|
||
Title = L("ImportCsv")
|
||
};
|
||
if (dialog.ShowDialog() != true) return;
|
||
|
||
try
|
||
{
|
||
var (imported, skipped) = TaskCsv.Import(System.IO.File.ReadAllText(dialog.FileName), _appData);
|
||
_ = SaveAsync();
|
||
OnPropertyChanged(nameof(TaskCountText));
|
||
|
||
var msg = string.Format(L("ImportSuccess"), imported);
|
||
if (skipped > 0) msg += " " + string.Format(L("ImportSkipped"), skipped);
|
||
MessageBox.Show(msg, L("AppTitle"));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show(string.Format(L("ImportError"), ex.Message), L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
private void ExportCsv()
|
||
{
|
||
var dialog = new Microsoft.Win32.SaveFileDialog
|
||
{
|
||
Filter = "CSV (*.csv)|*.csv",
|
||
Title = L("ExportCsv"),
|
||
FileName = "tasks.csv"
|
||
};
|
||
if (dialog.ShowDialog() != true) return;
|
||
|
||
try
|
||
{
|
||
// UTF-8 with BOM so Excel shows umlauts correctly.
|
||
System.IO.File.WriteAllText(dialog.FileName, TaskCsv.Export(_appData), new UTF8Encoding(true));
|
||
MessageBox.Show(L("ExportSuccess"), L("AppTitle"));
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show(string.Format(L("ExportError"), ex.Message), L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
public async Task SaveAsync()
|
||
{
|
||
try
|
||
{
|
||
await _dataService.SaveAsync(_appData);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MessageBox.Show($"{L("SaveError")}: {ex.Message}", L("AppTitle"), MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
public void Cleanup()
|
||
{
|
||
_reminderTimer.Stop();
|
||
}
|
||
|
||
/// <summary>Synchronous last save on exit – an async save still running would be cut off.</summary>
|
||
public void FlushSave()
|
||
{
|
||
try { _dataService.Save(_appData); }
|
||
catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[FlushSave] {ex.Message}"); }
|
||
}
|
||
}
|
||
}
|