#nullable enable
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using ReminderOrganizer.Core;
using ReminderOrganizer.Models;
using ReminderOrganizer.ViewModels;
namespace ReminderOrganizer
{
public partial class MainWindow : Window
{
private const string IconUri = "pack://application:,,,/Assets/app.ico";
private readonly MainViewModel _viewModel;
private System.Windows.Forms.NotifyIcon? _notifyIcon;
private bool _initialized;
private bool _trayHintShown;
private Point _dragStart;
public MainWindow()
{
InitializeComponent();
_viewModel = ServiceLocator.Services.GetService(typeof(MainViewModel)) as MainViewModel
?? throw new InvalidOperationException("MainViewModel not found");
DataContext = _viewModel;
_viewModel.ThemeChanged += (_, dark) => ApplyTheme(dark, animate: true);
_viewModel.EditTaskRequested += OnEditTaskRequested;
_viewModel.PropertyChanged += OnViewModelPropertyChanged;
TrySetWindowIcon();
Loaded += async (_, _) => await InitializeOnceAsync();
StateChanged += MainWindow_StateChanged;
}
/// Autostart: create the window (tray + timer) without showing it.
public async void StartHidden()
{
new WindowInteropHelper(this).EnsureHandle();
await InitializeOnceAsync();
}
private async System.Threading.Tasks.Task InitializeOnceAsync()
{
if (_initialized) return;
_initialized = true;
SetupTrayIcon();
await _viewModel.InitializeAsync();
ApplyTheme(_viewModel.IsDarkMode, animate: false);
SyncTreeSelection();
}
public void OnAppExit()
{
if (!_initialized) return;
_viewModel.Cleanup();
_viewModel.FlushSave();
}
private void TrySetWindowIcon()
{
try
{
Icon = System.Windows.Media.Imaging.BitmapFrame.Create(new Uri(IconUri));
}
catch
{
// no Assets\app.ico yet – Windows default icon
}
}
private void OnViewModelPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName is nameof(MainViewModel.SelectedFolder) or nameof(MainViewModel.IsUpcomingMode))
SyncTreeSelection();
}
/// TreeView.SelectedItem is read-only – mirror the view model selection onto the container.
private void SyncTreeSelection()
{
Dispatcher.BeginInvoke(() =>
{
if (_viewModel.IsUpcomingMode)
{
if (FolderTree.SelectedItem != null &&
FolderTree.ItemContainerGenerator.ContainerFromItem(FolderTree.SelectedItem) is TreeViewItem sel)
sel.IsSelected = false;
return;
}
var folder = _viewModel.SelectedFolder;
if (folder != null && FolderTree.ItemContainerGenerator.ContainerFromItem(folder) is TreeViewItem item && !item.IsSelected)
{
item.IsSelected = true;
item.BringIntoView();
}
}, System.Windows.Threading.DispatcherPriority.Loaded);
}
private void UpcomingEntry_Click(object sender, MouseButtonEventArgs e)
{
_viewModel.ShowUpcomingCommand.Execute(null);
}
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
bool ctrl = (Keyboard.Modifiers & ModifierKeys.Control) != 0;
if (ctrl && e.Key == Key.N)
{
if (_viewModel.AddTaskCommand.CanExecute(null)) _viewModel.AddTaskCommand.Execute(null);
e.Handled = true;
}
else if (ctrl && e.Key == Key.F)
{
SearchBox.Focus();
SearchBox.SelectAll();
e.Handled = true;
}
else if (e.Key == Key.Escape && (SearchBox.IsKeyboardFocusWithin || _viewModel.SearchText.Length > 0))
{
_viewModel.ClearSearchCommand.Execute(null);
FolderTree.Focus();
e.Handled = true;
}
else if (ctrl && e.Key == Key.Z && _viewModel.IsUndoVisible)
{
_viewModel.UndoCommand.Execute(null);
e.Handled = true;
}
else if (e.Key == Key.Delete && !SearchBox.IsKeyboardFocusWithin && _viewModel.SelectedTask != null)
{
_viewModel.DeleteTaskCommand.Execute(_viewModel.SelectedTask);
_viewModel.SelectedTask = null;
e.Handled = true;
}
}
private void OnEditTaskRequested(object? sender, ReminderTask? task)
{
if (task == null) return;
var taskWindow = new TaskWindow(task, _viewModel.IsDarkMode, _viewModel.Categories) { Owner = this };
if (taskWindow.ShowDialog() == true)
{
_ = _viewModel.SaveAsync();
}
}
private void ApplyTheme(bool isDarkMode, bool animate)
{
Theme.Apply(Resources, isDarkMode);
if (!animate || ThemeTransitionOverlay == null) return;
var overlay = ThemeTransitionOverlay;
overlay.Background = new SolidColorBrush(isDarkMode ? Color.FromRgb(0x12, 0x12, 0x18) : Color.FromRgb(0xF1, 0xF5, 0xF9));
var fadeIn = new DoubleAnimation(0, 0.3, TimeSpan.FromMilliseconds(100));
var fadeOut = new DoubleAnimation(0.3, 0, TimeSpan.FromMilliseconds(200));
fadeIn.Completed += (s, args) => overlay.BeginAnimation(OpacityProperty, fadeOut);
overlay.BeginAnimation(OpacityProperty, fadeIn);
}
private void MainWindow_StateChanged(object? sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
HideToTray();
}
}
private void HideToTray()
{
Hide();
if (!_trayHintShown && _notifyIcon != null)
{
_trayHintShown = true;
_notifyIcon.ShowBalloonTip(3000, _viewModel.L("AppTitle"), _viewModel.L("MinimizedToTray"), System.Windows.Forms.ToolTipIcon.Info);
}
}
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ClickCount == 2)
{
MaximizeRestore();
}
else if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
WindowState = WindowState.Minimized;
}
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
{
MaximizeRestore();
}
private void MaximizeRestore()
{
if (WindowState == WindowState.Maximized)
{
WindowState = WindowState.Normal;
MaximizeButton.Content = "";
}
else
{
// WindowStyle=None would cover the taskbar – limit to the work area.
MaxHeight = SystemParameters.WorkArea.Height + 8;
MaxWidth = SystemParameters.WorkArea.Width + 8;
WindowState = WindowState.Maximized;
MaximizeButton.Content = "";
}
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
HideToTray();
}
private void SetupTrayIcon()
{
System.Drawing.Icon icon = System.Drawing.SystemIcons.Information;
try
{
var res = Application.GetResourceStream(new Uri(IconUri));
if (res != null) icon = new System.Drawing.Icon(res.Stream);
}
catch { }
_notifyIcon = new System.Windows.Forms.NotifyIcon
{
Icon = icon,
Visible = true,
Text = "Reminder Organizer"
};
Services.NotificationService.SharedTrayIcon = _notifyIcon;
var menu = new System.Windows.Forms.ContextMenuStrip();
menu.Items.Add(_viewModel.L("Open"), null, (s, e) => ShowMainWindow());
menu.Items.Add(_viewModel.L("Exit"), null, (s, e) =>
{
_viewModel.Cleanup();
Application.Current.Shutdown();
});
_notifyIcon.ContextMenuStrip = menu;
_notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
_notifyIcon.BalloonTipClicked += (s, e) => ShowMainWindow();
}
private void ShowMainWindow()
{
Show();
if (WindowState == WindowState.Minimized) WindowState = WindowState.Normal;
Activate();
}
private void FolderTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs