355 lines
14 KiB
C#
355 lines
14 KiB
C#
using System;
|
||
using System.Collections;
|
||
using System.Collections.ObjectModel;
|
||
using System.Collections.Specialized;
|
||
using System.ComponentModel;
|
||
using System.Diagnostics;
|
||
using System.Linq;
|
||
using System.Threading.Tasks;
|
||
using System.Windows;
|
||
using System.Windows.Controls;
|
||
using System.Windows.Input;
|
||
using System.Windows.Data;
|
||
using QoSManager.Models;
|
||
using QoSManager.Services;
|
||
|
||
namespace QoSManager.Views
|
||
{
|
||
public partial class MainWindow : Window
|
||
{
|
||
private readonly QoSService _qosService;
|
||
private readonly LoggingService _loggingService;
|
||
private readonly ObservableCollection<QoSPolicy> _policies;
|
||
private bool _loggingEnabled = false;
|
||
private bool _isInitialized = false;
|
||
|
||
public MainWindow()
|
||
{
|
||
InitializeComponent();
|
||
|
||
_policies = new ObservableCollection<QoSPolicy>();
|
||
|
||
DataContext = this;
|
||
PoliciesDataGrid.ItemsSource = _policies;
|
||
|
||
// Load settings first to get logging preference
|
||
LoadSettings();
|
||
|
||
// Create services after settings are loaded
|
||
_loggingService = new LoggingService();
|
||
_qosService = new QoSService();
|
||
_qosService.SetLoggingEnabled(_loggingEnabled);
|
||
|
||
// Set logging enabled state for App
|
||
((App)Application.Current).SetLoggingEnabled(_loggingEnabled);
|
||
|
||
InitializeEventHandlers();
|
||
|
||
// Initialize checkbox state
|
||
LoggingCheckBox.IsChecked = _loggingEnabled;
|
||
|
||
// Hide settings panel initially and show it after UI is fully loaded
|
||
SettingsPanel.Visibility = Visibility.Collapsed;
|
||
|
||
// Don't log startup - let user enable logging manually if needed
|
||
|
||
LoadPolicies();
|
||
|
||
// Show settings panel and mark initialization as complete after UI loads
|
||
Dispatcher.BeginInvoke(() => {
|
||
// Always show checkboxes panel with current settings state
|
||
SettingsPanel.Visibility = Visibility.Visible;
|
||
_isInitialized = true;
|
||
|
||
// Auto-refresh QoS policies disabled on startup to prevent unwanted behavior
|
||
// User must manually enable auto-refresh if needed
|
||
});
|
||
}
|
||
|
||
public ObservableCollection<QoSPolicy> Policies => _policies;
|
||
|
||
private void InitializeEventHandlers()
|
||
{
|
||
AddPolicyButton.Click += AddPolicyButton_Click;
|
||
DeletePolicyButton.Click += DeletePolicyButton_Click;
|
||
RefreshButton.Click += RefreshButton_Click;
|
||
LogButton.Click += LogButton_Click;
|
||
LoggingCheckBox.Checked += LoggingCheckBox_Checked;
|
||
LoggingCheckBox.Unchecked += LoggingCheckBox_Unchecked;
|
||
ExitButton.Click += ExitButton_Click;
|
||
PoliciesDataGrid.BeginningEdit += PoliciesDataGrid_BeginningEdit;
|
||
PoliciesDataGrid.CellEditEnding += PoliciesDataGrid_CellEditEnding;
|
||
}
|
||
|
||
private void LoadSettings()
|
||
{
|
||
try
|
||
{
|
||
// Load preferences from Properties.Settings
|
||
_loggingEnabled = Properties.Settings.Default.EnableLogging;
|
||
}
|
||
catch
|
||
{
|
||
// Can't log here yet - logging service not created
|
||
}
|
||
}
|
||
|
||
private void SaveSettings()
|
||
{
|
||
try
|
||
{
|
||
// Save preferences to Properties.Settings
|
||
Properties.Settings.Default.EnableLogging = _loggingEnabled;
|
||
Properties.Settings.Default.Save();
|
||
}
|
||
catch
|
||
{
|
||
_loggingService.LogError("Error saving settings", _loggingEnabled);
|
||
}
|
||
}
|
||
|
||
private void PoliciesDataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
|
||
{
|
||
// Cancel any editing attempt - all fields are read-only
|
||
e.Cancel = true;
|
||
}
|
||
|
||
private void PoliciesDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
|
||
{
|
||
// Cancel any cell editing attempt - all fields are read-only
|
||
e.Cancel = true;
|
||
}
|
||
|
||
private async void LoadPolicies()
|
||
{
|
||
try
|
||
{
|
||
RefreshButton.IsEnabled = false;
|
||
_loggingService.LogInformation("Загрузка списка QoS-политик", _loggingEnabled);
|
||
|
||
var policies = await _qosService.GetPoliciesAsync();
|
||
|
||
_policies.Clear();
|
||
for (int i = 0; i < policies.Count; i++)
|
||
{
|
||
var policy = policies[i];
|
||
policy.Number = i + 1; // Add numbering starting from 1
|
||
_policies.Add(policy);
|
||
}
|
||
|
||
_loggingService.LogInformation($"Загружено политик: {policies.Count}", _loggingEnabled);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_loggingService.LogError($"Ошибка загрузки политик: {ex.Message}", _loggingEnabled);
|
||
CustomMessageBox.Show($"Не удалось загрузить список политик:\n\n{ex.Message}",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
finally
|
||
{
|
||
RefreshButton.IsEnabled = true;
|
||
}
|
||
}
|
||
|
||
private async void AddPolicyButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
var dialog = new PolicyEditWindow();
|
||
dialog.Owner = this;
|
||
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
|
||
if (dialog.ShowDialog() == true)
|
||
{
|
||
var newPolicy = dialog.GetPolicy();
|
||
|
||
try
|
||
{
|
||
bool created = await _qosService.CreatePolicyAsync(newPolicy, false);
|
||
|
||
if (created)
|
||
{
|
||
_loggingService.LogInformation($"Создана политика: {newPolicy.Name}", _loggingEnabled);
|
||
LoadPolicies();
|
||
CustomMessageBox.Show($"Политика '{newPolicy.Name}' создана успешно.",
|
||
"Успех", MessageBoxButton.OK, MessageBoxImage.Information);
|
||
}
|
||
else
|
||
{
|
||
CustomMessageBox.Show($"Политика с именем '{newPolicy.Name}' уже существует.",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_loggingService.LogError($"Ошибка создания политики: {ex.Message}", _loggingEnabled);
|
||
CustomMessageBox.Show($"Не удалось создать политику:\n\n{ex.Message}",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_loggingService.LogError($"Ошибка создания политики: {ex.Message}", _loggingEnabled);
|
||
CustomMessageBox.Show($"Не удалось создать политику:\n\n{ex.Message}",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
private async void DeletePolicyButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (PoliciesDataGrid.SelectedItem is QoSPolicy selectedPolicy)
|
||
{
|
||
try
|
||
{
|
||
var result = CustomMessageBox.Show(
|
||
$"Удалить политику '{selectedPolicy.Name}'?",
|
||
"Подтверждение",
|
||
MessageBoxButton.YesNo,
|
||
MessageBoxImage.Question);
|
||
|
||
if (result == MessageBoxResult.Yes)
|
||
{
|
||
await _qosService.DeletePolicyAsync(selectedPolicy.Name, false);
|
||
_loggingService.LogInformation($"Удалена политика: {selectedPolicy.Name}", _loggingEnabled);
|
||
LoadPolicies();
|
||
CustomMessageBox.Show($"Политика '{selectedPolicy.Name}' удалена успешно.",
|
||
"Успех", MessageBoxButton.OK, MessageBoxImage.Information);
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_loggingService.LogError($"Ошибка удаления политики: {ex.Message}", _loggingEnabled);
|
||
CustomMessageBox.Show($"Не удалось удалить политику:\n\n{ex.Message}",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
CustomMessageBox.Show("Выберите политику для удаления.",
|
||
"Внимание", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
}
|
||
|
||
private void RefreshButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
LoadPolicies();
|
||
}
|
||
|
||
private void RefreshPoliciesButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
_loggingService.LogInformation("Force refreshing QoS policies by user request", _loggingEnabled);
|
||
|
||
// Show progress message
|
||
CustomMessageBox.Show(
|
||
"Выполняется принудительное перечитывание QoS политик...\n\n" +
|
||
"Это может занять несколько секунд.\n" +
|
||
"После обновления может потребоваться перезапуск приложений.",
|
||
"Перечитывание политик", MessageBoxButton.OK, MessageBoxImage.Information);
|
||
|
||
// Force refresh QoS policies
|
||
_qosService.RefreshQoSPolicies();
|
||
|
||
// Reload policies list
|
||
LoadPolicies();
|
||
|
||
_loggingService.LogInformation("QoS policies refreshed successfully", _loggingEnabled);
|
||
|
||
// Show success message
|
||
CustomMessageBox.Show(
|
||
"QoS политики перечитаны",
|
||
"Успешно", MessageBoxButton.OK, MessageBoxImage.Information);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
_loggingService.LogError($"Error refreshing QoS policies: {ex.Message}", _loggingEnabled);
|
||
CustomMessageBox.Show($"Ошибка при перечитывании QoS политик:\n\n{ex.Message}",
|
||
"Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
private void LogButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
var logPath = _loggingService.GetLogFilePath();
|
||
Process.Start("notepad.exe", logPath);
|
||
_loggingService.LogInformation("Opened log file by user request", _loggingEnabled);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
CustomMessageBox.Show($"Could not open log file:\n\n{ex.Message}",
|
||
"Error", MessageBoxButton.OK, MessageBoxImage.Error);
|
||
}
|
||
}
|
||
|
||
private void LoggingCheckBox_Checked(object sender, RoutedEventArgs e)
|
||
{
|
||
_loggingEnabled = true;
|
||
_qosService.SetLoggingEnabled(_loggingEnabled);
|
||
((App)Application.Current).SetLoggingEnabled(_loggingEnabled);
|
||
if (_isInitialized)
|
||
{
|
||
_loggingService.LogInformation("Логирование включено", true);
|
||
}
|
||
}
|
||
|
||
private void LoggingCheckBox_Unchecked(object sender, RoutedEventArgs e)
|
||
{
|
||
// Log the disable action before actually disabling
|
||
if (_isInitialized && _loggingEnabled)
|
||
{
|
||
_loggingService.LogInformation("Логирование отключено пользователем", true);
|
||
}
|
||
_loggingEnabled = false;
|
||
_qosService.SetLoggingEnabled(_loggingEnabled);
|
||
((App)Application.Current).SetLoggingEnabled(_loggingEnabled);
|
||
}
|
||
|
||
|
||
private void ExitButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
Close();
|
||
}
|
||
|
||
private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
|
||
{
|
||
if (e.ChangedButton == MouseButton.Left)
|
||
{
|
||
DragMove();
|
||
}
|
||
}
|
||
|
||
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
WindowState = WindowState.Minimized;
|
||
}
|
||
|
||
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
|
||
}
|
||
|
||
private void CloseButton_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
Close();
|
||
}
|
||
|
||
protected override void OnStateChanged(EventArgs e)
|
||
{
|
||
base.OnStateChanged(e);
|
||
if (MaximizeButton != null)
|
||
MaximizeButton.Content = WindowState == WindowState.Maximized ? "\uE923" : "\uE922";
|
||
}
|
||
|
||
protected override void OnClosed(EventArgs e)
|
||
{
|
||
SaveSettings();
|
||
_loggingService?.Dispose();
|
||
_qosService?.Dispose();
|
||
base.OnClosed(e);
|
||
}
|
||
}
|
||
}
|